How to redirect on click with React Router?

Sometimes, we want to redirect on click with React Router.

In this article, we’ll look at how to redirect on click with React Router.

How to redirect on click with React Router?

To redirect on click with React Router, we can use the useHistory hook and the push method.

For instance, we write

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

const MyComponent = (props) => {
  const history = useHistory();

  const handleOnSubmit = () => {
    history.push(`/dashboard`);
  };
  //...
};

to call the useHistory hook to return the history object.

Then we call history.push with the URL we want to go to in the handleSubmit function to do the navigation.

Conclusion

To redirect on click with React Router, we can use the useHistory hook and the push method.