We can restrict certain routes if the person is not logged in. However, how can we restrict certain routes for rendering if the user is logged in? Below is my routing configuration:
<BrowserRouter>
<MenuBar />
<Routes>
<Route path='/' element={<PrivateRoute><Dashboard /></PrivateRoute>} />
<Route path='/register' element={<RegisterUser />} />
<Route path='/login' element={<LoginUser />} />
<Route path='/profile' element={<PrivateRoute><Profile /></PrivateRoute>} />
<Route path='/forgotpassword' element={<ForgotPassword />} />
</Routes>
</BrowserRouter>
PrivateRoute
function PrivateRoute({ children }) {
let user = JSON.parse(localStorage.getItem('user'));
return (
user ? children : < Navigate to={'/login'} />
);
}
I do not want to refactor using modifying all the components individually. Like once User
is logged in, they should not be able to go to certain screens like "/login"
or "/forgotpassword"
or "/register"
. What would be the suggested way to implement using only one PrivateRoute
? Is there a more optimal implementation which I might have missed?
2
Answers
You can apply the same logic as PrivateRoute .
make a Component
<AuthRoute>
and wrap your pages with it, if the use is authenticated redirect t "/". something like :another advice instead of wrapping each component with
<PrivateRoute>
or<AuthRoute>
you can nest them in Route which take<PrivateRoute>
as it’ element :and replace children in PrivateRoute with
<Outlet/>
For separation of concerns you really should create a separate component for protecting unauthenticated routes. It uses the same logic as the
PrivateRoute
but inverts the condition.Example:
If you insist on only updating the
PrivateRoute
component to do double-duty then I’d suggest this refactor to consume an auth condition and target route path for redirection.Example: