This is a common use case when we want to navigate in React router programmatically without using Link
or NavLink
components. There are many ways of doing that but since react router V5, it become very easy by using hook useHistory()
.
Suppose, you want to navigate to the route /superhero
. Now one way is to create an anchor using Link
component while the other way is manually pushing the route in history. Since this article is focused on programmatic route so we will use second approach.
Consider this example –
import { useHistory } from "react-router-dom"; function LoadSuperHero() { const history = useHistory(); function handleClick() { history.push("/superhero"); } return ( <button type="button" onClick={handleClick}> Go Super Hero </button> ); }
In this code, we are using useHistory()
hook of react router. First, we are importing it –
import { useHistory } from "react-router-dom";
Then we are declaring a history
constant which will hold the properties of useHistory()
.
const history = useHistory();
Now to programmatically navigate, just push a route in this constant –
history.push("/superhero");
Live Demo
Problem: Getting error Cannot read property ‘push’ of undefined in history.
Solution: You will get this error when you are trying to use react-router-dom
hooks outside the boundary of Router. By this I mean to say that you need to use all the router methods, hooks, classes and functions within the components which are wrapped inside <BrowserRouter>
.
We generally do this in index.js
file where we wrap the whole <App />
component within <BrowserRouter />
like this –
import ReactDOM from "react-dom"; import { BrowserRouter } from "react-router-dom"; import App from "./App"; const rootElement = document.getElementById("root"); ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter> , rootElement );