0

I have made an application where I am implementing routing using react-router-dom.

So the scenario is when a user logs in, he is redirected to localhost:3000/home url and home page is getting rendered. When he logs out he is coming to landing page which is on localhost:3000.

But if the user changes the url to localhost:3000 when logged in, everything is coming blank and he is showing as logged in, I believe this is the default behavior of routing.

The requirement is, to redirect user to home page until he is logged in even if he changes url by typing to localhost in the browser.

  • 1
    We can't help diagnose or debug code we can't see. Please edit your post to include a [mcve] so we can see what it's doing. If you need help with route protection and redirection see if this [answer](/a/66289280/8690857) helps. – Drew Reese Jul 01 '22 at 09:34

3 Answers3

0

add a condition to check if the user is log in and use the Navigate from react-router-dom to redirect the user . add this in your component

   return (
    { ("add condition here to check if user is login") ? (
        <Navigate to="/home " />
      ) : (<div>Component body</div>)
    }
    )
Mel Carlo Iguis
  • 126
  • 2
  • 9
0

Try, this if not log in then redirect to the login page and the login user then redirects to the login page.

 <HashRouter>
        {!auth.token && (
          <Routes>
            <Route path="/" element={<Login />} />
            <Route path="*" element={<Navigate to="/" />} />
          </Routes>
        )}
        {auth.token && (
          <>
              <Routes>
                <Route exact path="/home" element={<Home />} />
                <Route path="*" element={<Navigate to="/home" />} />
              </Routes>
          </>
        )}
</HashRouter>
Meet Majevadiya
  • 355
  • 2
  • 8
0

Hello your problem is easy to solve just structure your routes this way:

<Route
    exact
    path="/login"
    render={() => {
    if (userLoggedIn) {
       return <Redirect to="/home" />;
    } 
    return <LoginPage />; 
    }}
/>

Or do it this way:

<Route
    exact
    path="/home"
    render={() => {
    if (!userLoggedIn) {
       return <Redirect to="/login" />;
    } 
    return <HomePage/>; 
    }}
/>

I hope this helps you, if you need any other clarification please mention me in the comments below