Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
I want to restrict the page routing when user is logged in

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

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>)
    }
    )
about 4 years ago · Juan Pablo Isaza Report

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>

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!