I’m trying to create a dashboard page. I want the user to see the dashboard only when they are logged in, else direct to login page.
1- If user manually try to enter any other url that is not valid, it should redirect to login page if not logged in.
2- If user manually try to enter any other url that is not valid, it should redirect to dashboard page if they are logged in.
I managed to do this with the old react router but I am struggling to implement this on the new feature of react router.
Any advise would be helpful.
App.js
const App = () => {
const user = localStorage.getItem('user');
return (
<Routes>
<Route path='/' element={<ProtectedRoutes user={user} />}>
<Route index element={<Navigate to='/dashboard' />} />
<Route path='/dashboard/*' element={<Dashboard />} />
<Route path='*' element={<Navigate to='/dashboard' />} />
</Route>
<Route
path='/auth/*'
element={user ? <Navigate to='/dashboard' /> : <Authenticate />}
/>
</Routes>
);
};
ProtectedRoute.js
const ProtectedRoutes = ({ user }) => {
return user ? <Outlet /> : <Navigate to='/auth/login' />;
};
export default ProtectedRoutes;
Authenticate.js
const Authenticate = () => {
const set = () => {
localStorage.setItem('user', 'deep');
};
return (
<div className='auth'>
<div className='auth__screen'>
<Routes>
<Route path='register' element={<RegisterPage />} />
<Route path='verify-email/:verifyToken' element={<VerifyPage />} />
<Route path='login' element={<LoginPage />} />
<Route path='forgot' element={<ForgotPage />} />
<Route path='reset-password/:passwordToken' element={<ResetPage />} />
<Route path='*' element={<Navigate to='/auth/login' />} />
</Routes>
</div>
<button className='form__button' onClick={set}>
SET
</button>
</div>
);
};
If dashboard component renders sidebar, header and main components, above works but i like to use newer features like loader, error etc, just need need help to change so it works.
Any help would be apreaciated.