10
votes

I am trying to pass props through the React Router Link Component but the state remains undefined, does anyone have an idea of why?

The Route:

<Route path="/movie" component={Movie} render={props => 
<Movie {...props} />} />

The Link:

<Link to={{ pathname: '/movie', state: { fromMovieList: true}}} > 
Title </Link>

The component rendered from the path "/movie"

class Movie extends React.Component {

  render () {
    console.log(this.props.location.state); // undefined
    return (
      <div> Hello </div>
        )
      }
    }

export default Movie;
1

1 Answers

10
votes

You must wrap the Movie component with withRouter;

You can get access to the history object’s properties and the closest Route's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

export default withRouter(Movie);