React Router Dom v6 - redirecting to another route

Viewed 4563

I am using the following Router config:

<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/information" element={<Information />} />
  <Route path="*">
    <Navigate to="/" replace={true} />
  </Route>
</Routes>

I would like to navigate to home route and Home component every time when I type the route that is not recognized by the router. Since v6, there is no Redirect component, So I am trying to use Navigate.

Why my configuration is not working?

2 Answers

The new syntax/pattern to replicate the Redirect is to render the Navigate as the route element, and specify the replace prop.

RRDv5: <Redirect from="*" to="/" />

RRDv6: <Route path="*" element={<Navigate to="/" replace />} />

But the code sample above causes an infinite loop if you use it in the same way as the component from react-router v5 (that works just fine in this case actually)

<Redirect from="/foo" to="/foo/bar" />

like so:

<Route path="/foo" element={<Navigate replace to="/foo/bar" />} />

If route /foo doesn't exist - there is no page for this route

I don't really know how to deal with it just yet.

Related