user1991118 user1991118 - 13 days ago 5
Javascript Question

Access a react child object key and value pair

I have the following code to return a list element with key and value pairs from an object passed in by the parent component using the props. Why doesn't it work?

I get an error saying: TypeError: Cannot read property 'props' of undefined(…) The error is because of the this.props.data call in my return statement. It is not an issue with the data not being passed in through the props. I looked through the react output tree and my data object is indeed passed in to the child.

class Parent extends React.Component {
render(){
return (
<div>
{this.props.transactions.map(function(el,i) {
return <div key={i}>
<div>
{el.category}
</div>
<Child data={el.months}/>
</div>;
})}
</div>
);
}
}
class Child extends React.Component {
render(){
return (
<ul>
{Object.keys(this.props.data).map(function(key,index) {
return <li key={index}>{this.props.data[key]}</li>
})};
</ul>
);
}
}


Here is the data passed in by the parent component:

[{
"category": "Bills",
"month": {
"feb": 9,
"mar": 169,
"apr": 10,
"may": 867,
"jun": 394,
"jul": 787,
"aug": 1112,
"sep": 232,
"oct": 222,
"nov": 306,
"dec": 1096
}
}];

Answer

this inside the map function is referring to the function NOT the react class, so you need to pass this explicitly as follow:

(1) On the fly:

{
  Object.keys(this.props.data).map(function(key,index) {
    return <li key={index}>{this.props.data[index]}</li>
  }, this)
};

(2) In a separate method:

{
  Object.keys(this.props.data).map(this.listItems.bind(this))
};

and add listItems method to your class:

listItems(key, index) {
  return <li key={index}>{this.props.data[index]}</li>
}

Comments