乐闻世界logo
搜索文章和话题

How can I redirect in React Router v6?

1个答案

1

In React Router v6, the approach to redirection differs slightly from previous versions. The <Redirect> component has been removed in v6 and replaced by the <Navigate> component. First, I'll explain how to use the <Navigate> component for redirection, then provide a concrete example.

Using the <Navigate> Component for Redirection

In React Router v6, if you want to redirect within a component, you can use the <Navigate> component. This component accepts a to prop that specifies the target URL for redirection.

Basic Usage

jsx
import { Navigate } from 'react-router-dom'; function MyComponent() { const loggedIn = false; // Assume this is derived from the application's state for login status if (!loggedIn) { return <Navigate to="/login" />; } return <div>Welcome back!</div>; }

In this example, if the user is not logged in (with loggedIn set to false), they will be automatically redirected to the /login path.

Conditional Redirection

Assume you have a page that can only be accessed by users with administrator privileges. You can check the user's permissions before rendering the component and decide whether to redirect.

jsx
function AdminPage() { const isAdmin = userHasAdminRole(); // You need to implement this function to determine if the user has administrator privileges if (!isAdmin) { return <Navigate to="/home" replace />; } return <div>Admin page</div>; }

In this example, if the user is not an administrator, they will be redirected to the homepage (/home). The replace prop is optional and determines whether the current page in the browser history is replaced rather than adding a new entry.

Summary

Using the <Navigate> component for redirection is the recommended approach in React Router v6. It is straightforward and allows you to specify the redirection path via the to prop, enabling flexible use across components to meet various business requirements.

2024年6月29日 12:07 回复

你的答案