Home > Software design >  React Router v5 always redirecting
React Router v5 always redirecting

Time:10-17

I'm trying to handle unmatched routes in my app by having them redirect to the login screen, I've set my routes up like so:

<Switch>
{
    session.IsLoggedIn === false &&
    <Container fluid className="d-flex flex-column h-100">
        <Route exact path="/" component={ Login } />
        <Route path="/ResetPassword/:token" component={ ResetPassword } />      
        <Redirect to="/" />
    </Container>
}
</Switch>

With this setup though, even if I enter a legitimate route, i.e /ResetPassword/3245924, it still redirects to the login screen.

Note: I've gotten the above setup by following this tutorial: https://www.surajsharma.net/blog/react-router-default-route

How would I ensure that the legitimate routes are hit while redirecting on non handled routes?

CodePudding user response:

For best practice, all default paths should lead to your landing page...Routing during runtime is supposed to be managed by React backend. You could look into service workers for your own proxy. I suggest you remove the: session.IsLoggedIn === false && and just use a regular route initialization ...and use useState or onComponentDidMount to automatically load the content you want- you can make that page a component.

CodePudding user response:

You doesnt have wrapped your redirect in default router, therefore it will be always rendered/triggered

for correct behaviour wrap it in "default" route

<Switch>
{
    session.IsLoggedIn === false &&
    <Container fluid className="d-flex flex-column h-100">
        <Route exact path="/" component={ Login } />
        <Route path="/ResetPassword/:token" component={ ResetPassword } />      
        <Route path="*"><Redirect to="/" /></Route>
    </Container>
}
</Switch>
  • Related