Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router not updating URL on redirect

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.

like image 626
Sophia Price Avatar asked Jul 06 '18 08:07

Sophia Price


3 Answers

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.

like image 107
Jimi Pajala Avatar answered Oct 12 '22 18:10

Jimi Pajala


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}
/>
like image 36
Tholle Avatar answered Oct 12 '22 17:10

Tholle


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.

like image 1
Moonjsit Avatar answered Oct 12 '22 19:10

Moonjsit