I have an app using react-router-v4. I have a matching page which, unless you are logged in, you can't access. When a user is not logged in and tries to go to /match
they get redirected to /login
. My issue is that when the user is redirected to /login
the URL stays as /match. This is causing issues elsewhere in my code. How can I get React-Router to update the URL when the user is redirected to /login
? I am redirecting the page from my switch inside App.js. Here is an example of what my code looks like:
<Route
path='/match'
component= {
() => {
if (this.state.auth) return <HomePage />;
else return <LoginPage />;
}
}
/>
TL;DR
How can I get the URL to change to /login
if the user isn't logged in when trying to access /match
.
You probably have a little miss conception on how React Router works. In your example React Router works just as it should since you are just rendering components.
You should use React Router's <Redirect />
-component for redirecting user to new url.
You could achieve your desired behaviour with this example code.
<Route
path='/match'
render={
() => {
if(this.state.auth) return <HomePage />
return <Redirect to="/login" />
}
}
/>
<Route match="login" component={Login} />
You can also achieve same kind of behaviour inside component programmatically with using React Router's provided prop props.history.push('/login')
inside your component.
You could have a separate route for /login
, and use the Redirect component on your /match
route if the user is not logged in.
<Route
path='/match'
render={
() => {
if (this.state.auth) return <HomePage />;
else return <Redirect to='/login'/>;
}
}
/>
<Route
path='/login'
render={LoginPage}
/>
The logic for redirect should be part of component itself, not routes configuration. To make it reusable create HOC with redirect logic, and then just wrap paths that should be protected in routes config.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With