Skip to content Skip to sidebar Skip to footer

How To Properly Use Usehistory () From React-router-dom?

How to use useHistory() correctly? I can't make the transition from one react component to another. According to the instructions from the React documentation and also here on Stac

Solution 1:

This has changed in v6, useHistory is now useNavigate and we can use it as follows:

instead of:

const history = useHistory()
history.push('/')

we now use:

const navigate = useNavigate()
navigate('/')

Solution 2:

You can't just use the useHistory hook to redirect to another page. You need to properly set up your application in order to use React Router. Look at their examples starting from this https://reactrouter.com/web/example/basic

You need to wrap your entire application with <BrowserRouter /> which will give the history object you are looking for through the hook.

By the way, you don't give a relative file path to history.push as an argument, you must give a valid route that you typically setup using <Route /> component

Solution 3:

Using history.replace('/<route-name>') also works.

Solution 4:

you need to use it with react-router-dom. set your router config and then push it to that path. you can get more information by looking at documentation.

https://reactrouter.com/web/example/route-config

do not forget to set your switch components and your exact for root path.

Solution 5:

When you are applying history.push, is that your path name? history.push('/pathname') is the process I guess. You can see here: https://reactrouter.com/web/api/Hooks

Post a Comment for "How To Properly Use Usehistory () From React-router-dom?"