user17433353
user17433353

Reputation:

How do I make a 404 redirect with React Router 6?

In React Router 5 I could use a <redirect path='' /> but that has been removed in React Router 6. I think it's been replaced with <Navigate>, but that throws a security error for this use case.

Upvotes: 3

Views: 3126

Answers (2)

Khabir
Khabir

Reputation: 5854

Redirect is no longer in the react-router version 6. For react-router-dom v6, You can use Navigate instead of Redirect. Here is the example:

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

function App() {
    return (
        <>
            <Routes>
                <Route path="/404" element={<div>Page Not Found/div>} />
                <Route path="*" element={<Navigate replace to="/404" />} />
            </Routes>
        </>
    );
}

Upvotes: 6

Diogo M.F.
Diogo M.F.

Reputation: 11

As of v6:

  • Remove <Redirect>s inside <Switch>

  • Remove any <Redirect> elements that are directly inside a <Switch>.

// Change this:
<Switch>
  <Redirect from="about" to="about-us" />
</Switch>

// to this:
<Switch>
  <Route path="about" render={() => <Redirect to="about-us" />} />
</Switch>
  • Normal elements that are not inside a <Switch> are ok to remain. They will become <Navigate> elements in v6.

Upvotes: 0

Related Questions