Languages

React - useHistory was not found in 'react-router-dom'

0 points
Asked by:
Lily
548

I wanted to change route on button click and I got the following error:

Export 'useHistory' was not found in react-router-dom

My code:

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

const App = () => {
  const history = useHistory();
  const changeRoute = () => {
    history.push('/some/path/here');
  };
  return (
    <button onClick={changeRoute}>Go to some path</button>
  );
};

export default App;

How can I fix that? 

1 answer
0 points
Answered by:
Lily
548

The reason may be that you're using react-router-dom v6. In react-router-dom v6 the useHistory() hook was replaced with useNavigate().

Quick solution:

Import useNavigate hook and use navigate() method instead of history.push().

 

Practical example

After all, your could should look like this:

import { useNavigate } from 'react-router-dom'; // imports useNavigate hook

const App = () => {
  const navigate = useNavigate();  // uses useNavigate() instead of useHistory()

  const changeRoute = () => {
      navigate('/some/path/here');  // uses navigate() instead of history.push()
  };

  return (
    <button onClick={changeRoute}>Navigate to '/some/path/here'</button>
  );
};

export default App;

 

References

  1. useNavigate v6.6.2 | React Router
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join