23

I'am new to react-router (v4) and I was following the tutorial until this little problem :

This code works quite well

class App extends Component {
render() {
return (
    <Router>
       <div>
           <ul>
              <li><Link to="/link/value1" className="nav-link">Value1</Link></li>
              <li><Link to="/link/value2" className="nav-link">Value2</Link></li>
              <li><Link to="/link/value3" className="nav-link">Value3</Link></li>
         </ul>
         <hr/>
         <Route path="/link/:id" component={Generic}/>
       </div>
    </Router>
);
}
}

I defined a route to /link/:id with 3 links to it. Then I declare my "Generic" component like this (as a function) :

const Generic = ({ match }) => (
<div className="wrapper">
    <div className="section">
        <div className="container">
            <h3>Menu : {match.params.id}</h3>
        </div>
    </div>
</div>
)

This work as expected, no problem. But now, I'd like to declare my component with the ES6 class syntaxe like this :

class Generic extends React.Component {
constructor(props) {
    super(props);
}

render() {
    return (
        <div className="wrapper">
            <div className="section">
                <div className="container">
                    <h3>Menu : {this.props.params.id}</h3>
                </div>
            </div>
        </div>
    );
}
}

And here I have an error : Cannot read property 'id' of undefined

How can I access the "match.params.id" properties using the ES6 class approach?

Thank you for your help.

Cabrinha
  • 337
  • 1
  • 2
  • 9
  • 2
    Ok, I was searching the wrong object. The above example works fine if I change this.props.params.id to this.props.match.params.id – Cabrinha Jun 20 '17 at 07:31

2 Answers2

33

Use {this.props.match.params.id}

Riccardo Caroli
  • 431
  • 3
  • 3
7

If you need to pass some props to the component, use this approach:(eg)

<Route
  path='/home'
  render={(props) => <Home {...props} user = {this.state.user} />}
/>

In the target component you can now access both, the prop and the router parameter using this.props.user & this.props.match.params.id

Pransh Tiwari
  • 2,980
  • 1
  • 26
  • 33
  • You get ```Objects are not valid as a React child (found: object with keys {history, location, match, staticContext}). If you meant to render a collection of children, use an array instead. ``` – Josué Zatarain Oct 20 '20 at 12:21