How to programmatically navigate using React Router

How to programmatically navigate using React Router

In this post find the quick and simple solution for how to programmatically navigate using React Router - Quick Fix Series!

Will Mayger

A post by Will Mayger
August 04, 2021

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 = '', or window.location.assign('') 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>


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!

I hope this post has helped, but before you go I highly recommend that you checkout Pluralsight if you are interested in improving your software engineering skills, such as React, JavaScript, or Typescript (and much more).

Not only does Pluralsight provide you with all the learning material you need but it also let's you learn in a fun, interactive way and gives you the ability to see your current progress and level in a certain skill via their Skill Assessment tool which can help you see what you need to learn next to keep improving!

Some graphics used on this post were made using icons from flaticon.