Hey! If you're stuck with the "export useHistory was not found in react-router-dom" error while using React Router DOM, don't worry. It can be annoying, but we'll help you get it sorted out. In this simple guide, we'll tell you why it's happening and how to fix it easily.
problem code
import React from 'react';
import { useHistory } from 'react-router-dom';
function Home() {
const history = useHistory();
const handleClick = () => {
history.push('/about');
};
return (
<div>
<h1>My Component</h1>
<button onClick={handleClick}>Go to About</button>
</div>
);
}
export default Home;
Solution
To resolve this issue, you should replace the useHistory hook with the useNavigate hook because, in React Router version 6, the useHistory hook has been replaced with the useNavigate hook.
Here is an example of how you can replace:
import { useNavigate } from 'react-router-dom';
function Home() {
const navigate = useNavigate();
const handleClick = () => {
navigate('/about');
}
};
In this code, we switched from useHistory to useNavigate to fix the error. By making this change, we ensure our code works smoothly with React Router version 6. Also, note that we've replaced history.push() with the navigate() function.
This function needs two parameters: "to" and "options", where "options" is not always necessary but can be useful in certain situations, such as when you need to specify additional configurations for navigation, like replacing the current entry in the history stack or passing state along with the navigation.
If necessary, you can utilize it in this manner.
navigate('/about', { replace: true });
This { replace: true } is used as the "options" parameter with the navigate() function. This replaces the current entry in the history stack with the new route.
Here are the essential methods provided by the useNavigate hook
- Replace: history.push('/path') with navigate('/path')
- Replace: history.replace('/path') with navigate('/path', { replace: true })
- Replace: history.push({ pathname: '/path', state: data }) with navigate('/path', { state: data })
Last thought
Encountering errors, like "export useHistory was not found in react-router-dom," is common in web development. But don't worry! With the right guidance, these errors can serve as valuable learning opportunities. Understanding React Router v6 and making necessary adjustments ensures your projects work well and grow.
Important: Another error you might face is "(0 , _reactRouterDom.useHistory) is not a function." The good news is that the solution is the same! Both errors are the same thing. So, if you see "(0 , _reactRouterDom.useHistory) is not a function," just follow the same steps as for the first error.
If you have any questions regarding this solution or any other error related to web development, you can ask them in the question box below, and you will get a reply as soon as possible.