In react-router-dom
version 6 there is no render
prop for the Route
component. You can also simplify your PrivateRoute
wrapper component a bit, it doesn’t need to render more Routes
and Route
components.
Conditionally render the component’s children or navigate to log in.
const PrivateRoute = ({ auth: { isAuthenticated }, children }) => {
return isAuthenticated ? children : <Navigate to="/login" />;
};
Usage:
<Route
path="/dashboard"
element={
<PrivateRoute>
<Dashboard />
</PrivateRoute>
}
/>
A slightly improved version to allow nesting more private route components utilizes an outlet to handle rendering out nested routes.
const PrivateWrapper = ({ auth: { isAuthenticated } }) => {
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
};
Usage:
<Route element={<PrivateWrapper />}>
<Route path="/dashboard" element={<Dashboard />} />
</Route>