Sometimes, we want to navigate on path by button click in React Router v4.
In this article, we’ll look at how to navigate on path by button click in React Router v4.
How to navigate on path by button click in React Router v4?
To navigate on path by button click in React Router v4, we use the useHistory hook.
For instance, we write
import React from "react";
import { useHistory } from "react-router-dom";
export default () => {
const history = useHistory();
return <button onClick={() => history.push("/your/path")}>Click me</button>;
};
to call useHistory to get the history object.
Then we call history.push with the path we want to go to in the click handler of the button.
Conclusion
To navigate on path by button click in React Router v4, we use the useHistory hook.