[The easy way to] navigate React Router onClick


With React Router (react-router) it’s super easy to make links to navigate to other parts of your application. Here we’ll look at using React Router (v4 and v5) imperatively to allow navigation programmatically, such as in a button’s onClick event.

The easiest way to navigate React Router programmatically is to use the new (v5) useHistory() hook. This creates access to a history object which allows using the push() function to change the url in the browser.

React Router v5 useHistory() hook

Version 5 of React Router provides a convenient hook to get access to the history object. You can then use history.push() to navigate the browser to a new url.

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

const GoButton= () => {
  const history = useHistory();

  const handleClick = () => {
    history.push("/newurl");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go!
    </button>
  );
}Code language: JavaScript (javascript)

React Router v4 withHistory higher order component (HOC)

When using version 4 of React Router, there is a higher order component that can be wrapped around any component to inject a history object through props.

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

const GoButton = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/newurl') }}
  >
    Go!
  </button>
));Code language: JavaScript (javascript)

Whether you use v4 or v5 of React Router, either of the methods above will allow you to call history.push() whenever you need to navigate the user to a new location in your app. There are many other things you can do with the React Router history object. See below for a link directly to the history object documentation.

Additional Resources

Recent Posts