reactjs / react-router-tutorial

5.52k stars 1.75k forks source link

HowTo: Access props.params in react-router v4 #319

Closed TheoMer closed 7 years ago

TheoMer commented 7 years ago

OS: Windows 10 Pro React-router: 4.1.1 React: 15.5.4

So, I have recently updated my react-router v2 to v4 and cannot now access props.params.

My routing is as follows:

  render () {
    console.log('props.children = ', this.props.children);
    console.log('props = ', this.props);
    return (
      <div>
        <h1>
          <Link to="/">Flamingo City</Link>
        </h1>
        <Switch>
          <Route path={`${this.props.match.url}view/:postId`} render={() => (
            <Single {...this.props.children} {...this.props} />
            )} />
        </Switch>
      </div>
    );
  }

So attempting to do the following in Single.js now throws an undefined error message:

const postId = this.props.params.postId;

How do I resolve this?

TheoMer commented 7 years ago

The issue was resoved by doing the following:

          <Route path={`${this.props.match.url}view/:postId`} render={(props) => (
            <Single {...this.props} {...props} />
            )} />