React: 17.0.2
React Router: 6
Example: User are authenticated and try to access '/page2' through URL. They should fall through PrivateRoute flow and get to '/page2'.
Code:
const PublicRoutes = () => {
const { auth } = useAuth()
return auth ? <Navigate to={'/home'} replace /> : <Outlet />
}
const PrivateRoutes = () => {
const { auth } = useAuth()
return auth ? <Outlet /> : <Navigate to={'/signin'} replace />
}
export const Router = () => {
return (
<BrowserRouter>
<Routes>
<Route element={
<PublicLayout>
<PublicRoutes />
</PublicLayout>
}>
<Route path='/' element={<GetStarted />} />
<Route path='/signin' element={<SignIn />} />
<Route path='/signup' element={<SignUp />} />
</Route>
<Route element={
<PrivateLayout>
<PrivateRoutes />
</PrivateLayout>
}>
<Route path='/home' element={<Home />} />
<Route path='/page2' element={<Page2 />} />
</Route>
</Routes>
</BrowserRouter>
)
}
I've tried const location = useLocation() and use location.pathname but it gave some errors about multiple re-renders. Even the auth guide from Router 6 didnt work because location.state is null.
Some info about my authenticante flow: