1

I can't understand how to make a mandatory redirect when the condition is wrong.

{
  login ? (
   <Routes>
    <Route path='/profile' element={<Profile/>}/>
    <Route path='/chat' element={<Chat/>}/>
    <Route path='/' element={<UserList/>}/>
   </Routes>
   ) :
   (
   <Routes>
    <Route path='/login' element={<Login/>}/>
    <Navigate to='/login' state={{from: location}}/>
   </Routes>
   )
}

What's wrong?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
m3nnn0
  • 25
  • 1
  • 4

1 Answers1

2

You're creating a different set of routes based on the login status. That's wrong. Your routes shouldn't be conditioned. What you want instead is redirect (the term in V6 is navigate) the user from the page he's not allowed to access to the one he is. Again, this will be hard to achieve if the requested route doesn't exist.

Here is how you might tackle it:

<Routes>
  <Route path="/" element={<PublicPage />} />
  <Route path="/login" element={<LoginPage />} />
  <Route
    path="/protected"
    element={
      <RequireAuth>
        <ProtectedPage />
      </RequireAuth>
    }
  />
</Routes>

And:

const RequireAuth = () => {
  let auth = useAuth();

  if (!auth.user) {
    return <Navigate to="/login" />;
  }

  return children;
}
tavoyne
  • 5,591
  • 2
  • 14
  • 24