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
jsximport { 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.
jsxfunction 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.