Home > Software engineering >  why Navigate component wont redirect to home page after login?
why Navigate component wont redirect to home page after login?

Time:01-02

import Navbar from "./components/Navbar"
import Home from "./routes/Home"
import Signup from "./routes/Signup"
import Login from "./routes/Login"
import useAuthContext from "./hooks/useAuthContext"
import { Navigate } from "react-router-dom"
export default function App() {
  const { user } = useAuthContext()
  const router = createBrowserRouter(
    createRoutesFromElements(
      <Route path="/" element={<Navbar />}>
        <Route index element={!user ? <Navigate to="/login" /> : <Home />} />
        <Route path="/signup" element={<Signup />} />
        <Route path="/login" element={<Login />} />
      </Route>
    )
  )
  return <RouterProvider router={router} />
}

First it shows the login page, after I login it will stay on login page. how do I fix this?

I did try many things. it wont worked, i know in v5 I can use redirect component to redirect page.

CodePudding user response:

You have code that redirects from / to /login when the user is logged out:

<Route index element={!user ? <Navigate to="/login" /> : <Home />} />

You don't have code that redirects from /login to / when the user is logged in.

You need to add a <Navigate> in your /login route, either at the top level or inside of your Login component.

This is the simplest solution:

<Route path="/login" element={user ? <Navigate to="/"> : <Login />} />

(note: Navigate is the v6 equivalent of Redirect)

  • Related