Redirection in React Router Dom v6

Viewed 242

What is the correct process for re-directions in v6? I was previously using the following code in v5, which was working fine:

<Route path="/login">
  {user ? <Redirect to="/" /> : <LoginStandard />}
</Route>

However, I would like to use the same logic in this version. When my user has logged in, I would like to re-direct.

<Route path="/login">
  <Route index element={<LoginStandard />} />
</Route>
2 Answers

With React Router Dom v6 you redirect with Navigate instead of Redirect. Something like so:

import {Navigate} from "react-router-dom";
<Route path="/login">
   { user ? <Navigate to="/" /> : <LoginStandard/>}
</Route>

Use the Navigate component to redirect. The conditional rendering logic still needs to be applied and components rendered out on the Route component's element prop.

Example:

<Route
  path="/login"
  element={user ? <Navigate to="/" replace /> : <LoginStandard />}
/>

It is often considered better practice to abstract this into a custom route protection component that conditionally renders an Outlet for nested routes or the Navigate component.

Example:

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

const AnonymousRoute = ({ user }) => user
  ? <Navigate to="/" replace />
  : <Outlet />;

...

<Route element={<AnonymousRoute user={user} />}>
  <Route path="/login" element={<LoginStandard />} />
  ... other anonymous routes ...
</Route>
... other routes
Related