Another great hook that is available to React is the useHistory() hook. This hook gives you access to the history object from react-router-dom, which you can use to navigate. The useHistory hook then allow you to set navigate programmatically to other routes in your application by using push and replace methods.
To use this hook, you will first need to install react-router-dom.
npm install react-router-dom
Once installed, you will need to import useHistory into your app and create a history variable.
Import { useHistory } from ‘react-router-dom
const history = useHistory()
With the history variable created, you can now “push” routes to the history object. This will cause your application to navigate to that pushed location. This is usually handled with a function that can attached to the onClick event on a button or link
const goHome = () => {
history.push(“/”)
}
<button onClick={goHome}>Home</button>
Now, when the home button is clicked, your app will redirect to the component that is set to the “/” route. Besides the import call, all of this will need to be created inside of the functional component. And as a whole, it may look something like this:
import { useHistory } from 'react-router-dom';
const App = () => {
const history = useHistory();
const goHome = () => {
history.push("/");
}
return (
<div>
<h1>Hi there!</h1>
<button onClick={goHome}>Home</button>
</div>
);
};
Top comments (0)