21

New version of react-router-dom (v6.0.0) doesn't identify "Redirect". What is the alternative for it?

Ali Nematollahi
  • 221
  • 1
  • 2
  • 5

5 Answers5

38

Redirecting alone is done via the Navigate component with the replace prop specified.

<Navigate replace to="/" />

If you want to replicate RRDv5's Redirect component redirecting from a path then you need to combine with a Route.

<Route path="/somePath" element={<Navigate replace to="/" />} />
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
6

If you aren't server rendering your app you can still redirect on the initial render in the client like this:

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

    function App() {
      return (
        <Routes>
          <Route path="/home" element={<Home />} />
          <Route path="/" element={<Navigate replace to="/home" />} />
        </Routes>
      );
    }

In the above example, when someone visits /, they will automatically be redirected to /home, same as before.

Please note however that this won't work when server rendering because the navigation happens in a React.useEffect().

Have a look at Redirects in React Router v6 for some deeper details.

zerocewl
  • 11,401
  • 6
  • 27
  • 53
3

Redirecting in react-router-dom v6 is done with the <Navigate> Component with replace props.

Step 1:

import { Navigate } from 'react-router-dom';

Step 2:

<Routes>
    <Route path='/' element={<Navigate replace to='/search' />} />
</Routes>
Haroon Hayat
  • 329
  • 2
  • 4
1

Here is what the react-router-dom teams said on the matter of redirects when that removed that API in v6: https://github.com/remix-run/react-router/blob/main/docs/upgrading/reach.md#redirect-redirectto-isredirect

-3

In v6.2.* Just add a Route with path to *

<Routes>
  <Route path="/" element={<App />}>
    <Route path="expenses" element={<Expenses />} />
   
    <Route
      path="*"
      element={
        <main style={{ padding: "1rem" }}>
          <p>There's nothing here!</p>
        </main>
      }
    />
  </Route>
</Routes>

Official Doc

Mbanda
  • 968
  • 11
  • 21