Categories
React Answers

How to programmatically navigate using React Router and JavaScript?

Spread the love

To programmatically navigate using React Router and JavaScript, we can use the useHistory hook.

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}>
      Go home
    </button>
  );
};

to call the useHistory hook to return the history object.

Then we define the handleClick function that calls history.push to navigate to the /home page.

And then we set the onClick prop toi handleClick to call handleClick when we click oin the button.

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 *