EN
React - useHistory was not found in 'react-router-dom'
1
answers
0
points
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
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
0 comments
Add comment