Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Stack Overflow, I cannot make the transition from App.js to MyComponent.js.

For example - I am trying

/* **App.js ** */
/* Import modules */
import React from 'react';
import { useHistory } from 'react-router-dom'; // version 5.2.0

function App()
{
    let history = useHistory ();
    const handleClick = () => {
       history.push ('./pages/MyComponent');
    }    

    return (
       <div className="App">
          <button onClick={handleClick}>Next page ==></button>
       </div>
    );
}

I also tested this example, but the output throws the following error when the button is pressed:

TypeError: Cannot read property 'push' of undefined

Does something seem to be leaking to me or is there a mistake on Babel's side?

Project react structure:

+ Root/
    + src/
        - App.js
        - index.js
        + pages/
            - MyComponent.js
    
like image 285
Petr Fořt Fru-Fru Avatar asked Nov 14 '20 21:11

Petr Fořt Fru-Fru


People also ask

How do I import useHistory in react dom router?

Through the history object, we can access and manipulate the current state of the browser history. All we need to do is to call the useHistory hook inside a functional component: import { useHistory } from 'react-router-dom'; const App = () => { const history = useHistory(); const redirect = () => { history.

What is useHistory from react router dom?

useHistory: This is one of the most popular hooks provided by React Router. It lets you access the history instance used by React Router. Using the history instance you can redirect users to another page.

What we can use instead of useHistory in react?

Use useNavigate instead of useHistory.


2 Answers

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('/')
like image 176
HibaHasan Avatar answered Sep 28 '22 17:09

HibaHasan


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

like image 35
Kyubbbbbb Avatar answered Sep 28 '22 16:09

Kyubbbbbb