I have a route set up to render a component:
<Route exact path="/page/:id" location={this.props.location} key={this.props.location.key} render={({ location }) => ( <PageStart key={this.props.location.key} /> )} />
Then inside that component (PageStart) I have:
this.props.match.params.id
But it throws an error:
Cannot read property 'params' of undefined
Passing props when simply calling component={}
seems to work fine but not in a render function. Why?
The "Cannot read property 'props' of undefined" error occurs when a class method is called without having the correct context bound to the this keyword. To solve the error, define the class method as an arrow function or use the bind method in the classes' constructor method.
You need to wrap it in withRouter - that injects the URL variables into your props. Show activity on this post. import React, { Component } from 'react'; class Student extends Component { render() { const { studentId } = this. props.
React parameters are used in React routing, where we have parameters we need to access in the route. For example, if we had a route such as <Route path=”/:id” /> we could access that particular string or value in the route by calling the useParams hook. let { id } = useParams();
Because with render
you are not passing the default props passed by the router into component, like match, history etc.
When you write this:
<PageStart key={this.props.location.key} />
It means no props
value in PageStart
component.
Write it like this:
render = {props => <PageStart {...props} key={this.props.location.key} /> } />
Now {...props}
will pass all the value into PageStart
component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With