Home > OS >  How can I redirect login to current page in react js?
How can I redirect login to current page in react js?

Time:05-07

I create a single page application using react. I create protected route but after login, I can access login page after login. If I try to go login route I can access. How can I prevent to this. If I try to access login page It will redirect login to my current page.

CodePudding user response:

This is assuming you're using react-router, but you essentially want to be able to check if the user is logged in, and if they are then you want to conditionally remove the <Route... definition for login.

example:

export function App() {
return (
  <Routes>
    <Route path="/" element={<DataPipelineEditorView />} />
    {isUserLoggedIn ? null : <Route path="/login" element={<Login />} />}
  </Routes>
}

You'll just need to figure out how to populate the isUserLoggedIn. If you have a react context (or some other means) that holds the state of your user's login session (or maybe a local storage cookie) you can check it in the component and render the Routes accordingly.

If you're not using react router then share your code and we can go from there!

CodePudding user response:

you can use

  Router,
  Switch,
  Route,
  Link

for it.

here I put a example for route example, hope it will help you.

  • Related