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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.