Programmatically Navigate Using React Router and Hooks
Nick Scialli • May 23, 2020 • 🚀 1 minute read
If you’re using React Router 5.1.0 or later and React 16.8.0 or later, you can now programmatically navigate with ease using the useHistory
hook!
Let’s look at a quick example. Say you want to navigate somewhere on a button click. Previously, you might have had to pass the history
object down your React component tree. With the new useHistory
hook, you no longer need to do that!
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
function goToLogin() {
history.push('/login');
}
return (
<button type="button" onClick={goToLogin}>
Login
</button>
);
}
And there you have it! We’ve retrieved our history
object using a hook inside our function component. We can now use the push
method on history
to navigate the user somewhere!
Nick Scialli is a software engineer at the U.S. Digital Service.