Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property ‘params’ of undefined (React Router 4)

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?

like image 290
Matt Saunders Avatar asked Sep 13 '17 12:09

Matt Saunders


People also ask

How do you fix Cannot read property of undefined In react?

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.

How do I get params from URL in react class component?

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.

What is params in Reactjs?

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();


1 Answers

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.

like image 161
Mayank Shukla Avatar answered Sep 21 '22 19:09

Mayank Shukla