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 redirect.
<Route path="/login">
<Route index element={<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
With React Router Dom v6
, you redirect with Navigate
and useNavigate
instead of Redirect
and useHistory
used in v5
. Something like below. See the comments:
import { Navigate, useNavigate } from "react-router-dom";
export default function Foo() {
const navigate = useNavigate();
// Use navigate returned by useNavigate when you are outside of JSX
navigate("/");
// Use Navigate the imported component when you are inside of JSX
return <Route path="/login">{user ? <Navigate to="/" /> : <LoginStandard />}</Route>;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With