how to use history instance while using react routers v6?

Viewed 8294

I'm using react-router v6 and I have to use history instance.

I've installed it using

yarn add history react-router-dom@next

One way of using history instance I guess it must be with v5 is to use useHistory hook imported from react-router-dom

this code is running fine with v5 but with v6 it is not working

import { useHistory } from "react-router-dom";

const history = useHistory();

const onRedirectCallback = (appState) => {
        history.push(appState?.returnTo || window.location.pathname);
};

with v6 version, I'm having this error

Attempted import error: 'useHistory' is not exported from 'react-router-dom'.

2 Answers

You need to use useNavigate hook and new navigate API.

import { useNavigate } from "react-router-dom";

const navigate = useNavigate();

const onRedirectCallback = (appState) => {
        navigate(appState?.returnTo || window.location.pathname);
};
// import

const { useNavigate } from 'react-router-dom'

const navigate = useNavigate()

navigate({ pathname: './webpage/path' }) 

navigate({ pathname: './webpage/path' }, { replace: true })
Related