How to programmatically navigate using React Router?

Sometimes, we want to programmatically navigate using React Router.

In this article, we’ll look at how to programmatically navigate using React Router.

How to programmatically navigate using React Router?

To programmatically navigate using React Router, we can use the history.push method.

For instance, we write

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

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

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

  return (
    <button type="button" onClick={handleClick}>
      home
    </button>
  );
}

to call the useHistory to return the history object.

Then we call history.push with the URL we want to go to in handleClick to redirect to the URL.

Conclusion

To programmatically navigate using React Router, we can use the history.push method.