Private Route in react-router v6
Dec 24, 2021
Private routes in v5 and below were done in a specific way using a custom component mostly named PrivateRoute
But taking a look at v6 docs it seems that things changed a little bit, and we need to think a little bit different about it.
# In the react-router 6 you have to use Login instead of Redirect
- *So what do we do? 🤔 We do some more adjustments to
PrivateRoute
function PrivateRoute({ children }) {
const auth = useAuth();
return auth ? children : <Navigate to="/login" />;
}
As you can see we changed Redirect
to Login
, and just return children
if a user is authenticated. And the usage of it also changes a little bit