Programmatically navigate using React Router v6

Adel Benyahia
4 min readNov 21, 2022
  1. Overview of the tutorial
  2. Let’s start coding
  3. Understanding the useNavigate() hook
  4. Understnding the navigate(-1) in useNavigate() hook
  5. Understanding the { replace:true } in useNavigate()

1. Overview of the tutorial

Programmatic navigation refers to when a user is redirected to a new page ( route) by clicking on an element (ex login button, logout link …)

In this article, we will explain how to navigate from one route to an other programmatically with React Router using the useNavigate() hook

2. Let’s start coding

We will not start from scratch, we will take the project from my tutorial “A practical guide to React Router v6”

In this project we have made an application using Reactjs and React Router v6 to navigate between different pages (routes): Dash, Login, Profile, Page not found)

3. Understanding th useNavigate() hook

We will use the React Router useNavigation

The useNavigate hook returns a function that lets you navigate programmatically,

The navigate function has two signatures:

. Either pass a To value (same type as <Link to>) with an optional second

{ replace, state } arg or
. Pass the delta you want to go in the history stack. For example, navigate(-1) is equivalent to hitting the back button.

Let’s take a look at the source code of <Login.js>

import "./styles.css";
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
export default function Login() {
const usernameRef = useRef();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
navigate(`/dash/${username}`);
};
useEffect(() => {
//usernameRef.current.focus();
}, []);

return (
<div className="App">
<h1>Login</h1>
<form onSubmit={handleSubmit} className="form__container">
<div className="form__controls">
<label htmlFor="username">Username</label>
<input
ref={usernameRef}
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form__controls">
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="form__controls">
<button className="button">Login</button>
</div>
</form>
</div>
);
}

in the function handleSubmit()

const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
navigate(`/dash/${username}`);
};

When the function is executed navigte(`/dash/${username}`) and the user will be redirected to “/dash/__username__”

4. Understanding the navigate(-1) in useNavigate() hook

In the <PageNotFound>

import { useNavigate } from "react-router-dom";
import "./styles.css";
export default function PageNotFound() {
const navigate = useNavigate();
return (
<div className="App">
<h1>
<span>4</span>
<span>0</span>
<span>4</span>
</h1>
<div>
<button
style={{ width: 200 }}
onClick={() => {
navigate(-1);
}}
>
Go back
</button>
</div>
</div>
);
}

In the Button onClick event

<button
style={{ width: 200 }}
onClick={() => {
navigate(-1);
}}
>
Go back
</button>

The function “navigate(-1)” will redirect the user to the page visited before the current page.

A call to navigate will push a new page into the history stack so the user can go back to this page.

5. Understanding the { replace:true } in useNavigate()

The useNavigate hook returns a function that lets you navigate programmatically, for example after a form is submitted. If using replace: true, the navigation will replace the current entry in the history stack instead of adding a new one.

You can pass replace: true to navigate, with that the current page in the history stack will be replaced with the new one.

Practical example

In <Login>

  1. With out { replace:true }

Our click function will look like this

const handleSubmit = async (e) => {
e.preventDefault();
navigate(`/dash/${username}`);
};

. From the Home page click on login button, you will be redirected to the Login page.

. Enter a user name (any username will be accepted),for example “adel”, you will be redirected to “/dash/adel”

. Try to go back using the browser go back button, you will be redirected to Login page because it’s the latest visited page before the Dash page (Home > Login > Dash)

No if we won’t to omit the login page?

Add {replace:true} to our navigate() function

const handleSubmit = async (e) => {
e.preventDefault();
navigate(`/dash/${username}`,{replace:true});
};

No on the Home page click on login again, then on the Login page, enter the username “adel” adn click the button login.

you will be redirected to the Dash page.

But in this case the History Stack of the browser will look like this (Home > Dash), the Login page is Omited

If you click on the browser go back button you will be redirected to the Home page

--

--

Adel Benyahia

Web application developer (HTML │ CSS │ JS | ReactJS | NextJS | NestJS | MERN)