Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
}];
like image 993
mo_maat Avatar asked Apr 28 '26 07:04

mo_maat


2 Answers

this inside the map function is referring to the function NOT the react component's instance, 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>
}

like image 134
Basim Hennawi Avatar answered Apr 30 '26 19:04

Basim Hennawi


@Basim already gave the correct answer. If you are using ES6, you can also do like this.

{Object.keys(this.props.data).map((key,index)=> {
        return <li key={index}>{this.props.data[key]}</li>
  })};
like image 35
Ved Avatar answered Apr 30 '26 19:04

Ved



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!