Home > Net >  React Router Dom v6 - redirecting to another route
React Router Dom v6 - redirecting to another route

Time:11-20

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?

CodePudding user response:

Here is the example from their docs

 <Routes>
    <Route path="/" element={<Layout />}>
      <Route index element={<Home />} />
      <Route path="about" element={<About />} />
      <Route path="dashboard" element={<Dashboard />} />

      {/* Using path="*"" means "match anything", so this route
            acts like a catch-all for URLs that we don't have explicit
            routes for. */}
      <Route path="*" element={<NoMatch />} />
    </Route>
  </Routes>

I think you need to put your catch all flag "*" under your root Route

<Routes>
    <Route path="/" element={<Home />}>
      <Route path="*" element={<Home />} />
    </Route>
    <Route path="/information" element={<Information />} />
  </Routes>

CodePudding user response:

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 />} />

  • Related