Alexander Solonik
Alexander Solonik

Reputation: 10250

How to send variable along with Redirect in Reactjs?

I have the following in my react app:

<PrivateRoute 
  path="/profile" 
  component={ Profile }
  authenticated={ this.state.authenticated }

/>

<PrivateRoute/> is basically just the below:

const PrivateRoute = ({ component : Component , authenticated : auth , ...rest }) => {
  return (
    <Route {...rest} render={ (props) => {
      return (
        auth ? <Component {...props} /> 
        : <Redirect 
            to={{
                pathname : '/login',
                state : {
                    from : props.location
                }
            }} />
      )
    } } />
  )
}

As you can see in the above code there is a auth variable , how do i send this variable to now i would like to send this variable alog with the <Redirect /> which basically loads the <Login /> component , but how exactly do i send the auth variable alog with the Redirect component ?

Upvotes: 0

Views: 927

Answers (2)

Siddharth Pachori
Siddharth Pachori

Reputation: 169

Use this.props.history.push and access that variable by this.props.location

Upvotes: 0

Dhananjay C
Dhananjay C

Reputation: 597

You can pass props data with Redirect like this:

const PrivateRoute = ({ component : Component , authenticated : auth , ...rest }) => {
return (
<Route {...rest} render={ (props) => {
  return (
    auth ? <Component {...props} /> 
    : <Redirect 
        to={{
            pathname : '/login',
            state : {
                from : {auth : auth}
            }
        }} />
  )
} } />

) }

and this is how you can access it:

this.props.location.state.auth

Upvotes: 2

Related Questions