TypeOfNaN

Programmatically Navigate Using React Router and Hooks

Nick Scialli
May 23, 2020

react router logo

If you’re using React Router 5.1.0 or later and React 16.8.0 or later, you can now programmatically navigate with ease using the useHistory hook!

Let’s look at a quick example. Say you want to navigate somewhere on a button click. Previously, you might have had to pass the history object down your React component tree. With the new useHistory hook, you no longer need to do that!

import { useHistory } from 'react-router-dom';

function MyComponent() {
  const history = useHistory();

  function goToLogin() {
    history.push('/login');
  }

  return (
    <button type="button" onClick={goToLogin}>
      Login
    </button>
  );
}

And there you have it! We’ve retrieved our history object using a hook inside our function component. We can now use the push method on history to navigate the user somewhere!

If you'd like to support this blog by buying me a coffee I'd really appreciate it!

Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli