9

I have an app using . 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.

2
  • Possible duplicate of Redirect to previous path on login - React Router v4 Commented Jul 6, 2018 at 8:22
  • 1
    @RagulParani Thanks, I have looked at the answer provided to that question and tried to implement it, however I am getting the error: 'Private Route is not defined'. I am using jsx, not tsx, so I tried taking out the const when adding the code to my file, which isn't working. Not sure how else to put that code into my file? Commented Jul 6, 2018 at 9:00

3 Answers 3

5

You probably have a little misconception 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 a component programmatically with using React Router's provided prop props.history.push('/login') inside your component.

Sign up to request clarification or add additional context in comments.

Comments

3

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}
/>

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.