Terry S
Terry S

Reputation: 58

Passing state in Redirect

I'm trying to make it so that when you login, you go to the home page. But when you type in a URL that doesn't exist, it will ask you to log in and then take you to a 404 page. I'm using React Router v4.

I console.log(this.props.location.state) to see the outcome.

// App.js
<BrowserRouter>
  <Menu />
  <MainTitle />
  <Switch>
    <Route path='/' exact component={Home} />
    <Route path='/login' component={Login} />
    <Route path='/error' component={Error} />
    <Route path='/leaderboard' component={LeaderBoard} />
    <Route path='/add' component={Add} />
    <Route path='/questions/:question_id' exact component={Info} />
    <Redirect from='*' to={{
      pathname: '/login',
      state: {
        fromError: true
      }
    }}/>
  </Switch>
</BrowserRouter>

// Login.js
const { fromError } = this.props.location.state
if(fromError){
  ...
} else {
  ...
}

Errors in the URL of the main part of the address work fine. For example: http://localhost:3000/leaderboooooard -> fromError = true http://localhost:3000/questionnnns/xj352vofupe1dqz9emx13r -> fromError = true

But on the route with http://localhost:3000/questions/:question_id, when the params is incorrect, it redirects to login BUT it doesn't set the fromEror to true. Any ideas? Thanks for the help.

Upvotes: 0

Views: 398

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282000

React router doesn't know which url param is correct and which is wrong. It just matches the path and provides the params as props to the rendered component.

Since you can determine if the param is valid or not, you can Redirect to login from the component itself

// In Info component render method

render() {
    if(!this.isValid(this.props.match.param. question_id)) {
        <Redirect  to={{
          pathname: '/login',
          state: {
            fromError: true
          }
        }}/>
    }
    // rest render logic
}

Upvotes: 1

Related Questions