When using React Router (react-router-dom) you have different ways to handle navigations to routes. Generally, you can programmatically navigate or have links that users can click to navigate.
This tutorial shows how to do programmatic navigation using a React router.
The useNavigate hook
Since version 6 of React Router, we can make use of the hook useNavigate to handle programmatic navigations.
The useNavigate is simple to use as shown in the example below. The usage is similar to the useHistory hook in the older versions of the package.
How to programmatically navigate using React Router
To navigate in react-router programmatically,
- import the useNavigate hook from react-router-dom
- call the navigate hook, passing the route you want to navigate to
Example
Let’s assume we want to navigate to the Privacy Policy page (“/privacy-policy”) when someone wants to sign up but has to read and agree to the privacy policy first:
import { useNavigate } from 'react-router-dom'; export default function SomePage() { const navigate = useNavigate(); const gotoPage = () => { navigate('/privacy-policy'); } return ( <> <button onClick={gotoPage}>Read our privacy policy</button> </> ); }