Categories
React Answers

How to redirect in React Router v6?

Spread the love

To redirect in React Router v6, we add the replace prop to the Route.

For instance, we write

import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";

//...
<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/lab" element={<Lab />} />
    <Route path="*" element={<Navigate to="/" replace />} />
  </Routes>
</BrowserRouter>

to add the * route that has the replace prop added to Navigate so that we redirect to the / route.

Then Home is rendered after the redirect is done.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *