Categories
JavaScript Answers React Answers

How to programmatically navigate using React Router?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *