Skip to content
react

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

Mar 2, 2023Abhishek EH2 Min Read
Fix: Export 'useHistory' was not found in react-router-dom

Have you started using or upgraded react router and started getting the following error?

1export 'useHistory' (imported as 'useHistory') was not found in 'react-router-dom'

In this article, we will see how to fix this issue.

The issue occurs because, in react-router version 6, useHistory hook was removed.

So now you might be wondering if it was removed, how do I access the browser history? how to navigate the user to another page? how to go back to the previous page? how to set a link as active if the user is on that page?

We have answers to all of your questions in this article!

In React Router 6, a new hook was introduced called useNavigate. Let's see how we can use the useNavigate hook.

You can navigate to another page as shown in the below code:

1import { useNavigate } from "react-router-dom"
2function App() {
3 const navigate = useNavigate()
4 const handleNavigation = () => {
5 navigate("/about")
6 }
7
8 return (
9 <div className="App">
10 <button onClick={handleNavigation}>Navigate</button>
11 </div>
12 )
13}

You can call the handleNavigation function whenever you want to navigate to /about page

Going back to the previous page

To go back to the previous page you can pass -1 instead of the URL.

1import { useNavigate } from "react-router-dom"
2
3//...
4const navigate = useNavigate()
5const goBack = () => {
6 navigate(-1)
7}

Setting active class

To set an active class, we need to know the current route. We can access the current route path using window.location.pathname. So we can set the active class as shown in the below code:

1<a
2 href="/home"
3 className={window.location.pathname === "/home" ? "active" : ""}
4>
5 Home
6</a>

You can alternatively use the useLocation hook to access the path as shown below:

1import { useLocation } from "react-router-dom"
2//...
3const location = useLocation()
4console.log({ pathname: location.pathname })

Do follow me on twitter where I post developer insights more often!

© 2024 CodingDeft.Com