In this quick post we will be covering how to programmatically navigate using React Router so you can solve this issue quickly and without having to look any further!
As with all my Quick Fix Series of posts, you will first find the problem described and then the solution just below.
Let’s get stuck in!
The Problem - Navigating programmatically using React Router
When you are using React Router it is a pretty common scenario that you will need to navigate programmatically between pages.
So to better describe the issue here, when I say programmatically navigating using React Router, I don’t mean via a link or button component from React Router, for example:
<Link to="/about">About</Link>
This is not classed as navigating programmatically because it is emulating what would happen if you used an anchor element in a non-react application.
Instead we want to find the equivalent for using something like window.location.href = 'https://example.com/example'
, or window.location.assign('https://example.com/example')
that can be called from anywhere in the application by JavaScript.
So how do we do this with React Router?
How to programmatically navigate using React Router
React router provides a react hook called useHistory which returns a value that enables us to do many things, one of which is to be able to navigate programmatically to a new route. By calling .push(newUrlHere)
it will then navigate us to that page as well as save it to the router history so that it can be accessible via the back button in the browser.
Here is an example of how you can use the useHistory react hook to programmatically navigate using React Router:
export default function ExampleComponent() {
const history = useHistory()
useEffect(() => {
setTimeout(() => history.push("/about"), 2000)
}, [history])
return (
<h1>This will automatically navigate to the about page after 2 seconds</h1>
)
}
Summary
There we have the quick fix to how to programmatically navigate using React Router, if you want more like this be sure to check out some of my other posts!