Using props in the .map function

Let's say I have the following render function on one of my components. From the parent, I passed the changeTid prop function.

Parent:

 <RequestsList data={this.state.data} changeTid={this.changeTid} /> 

Child:

(I am using ES6 classes)

 render() { var RequestNodes = this.props.data.map(function(request) { return ( <Request key={request.TID} changeTid={this.props.changeTid} /> ); }); return ( <div className="list-group">{RequestNodes}</div> ); } 

I cannot use this.props.changeTid in my map function, because this does not refer to what I do not want. Where can I bind it so that I can access my props ?

+8
javascript ecmascript-6 reactjs
source share
2 answers

You can set this for .map callback via second argument

 var RequestNodes = this.props.data.map(function(request) { /// ... }, this); 

or you can use the arrow function , which does not have its own this , and this inside it refers to the enclosing context

 var RequestNodes = this.props.data.map((request) => { /// ... }); 
+17
source share

If you are using ES6, you can use the arrow functions , which does not bind your own this

 var RequestNodes = this.props.data.map(request => { return ( <Request key={request.TID} changeTid={this.props.changeTid} /> ); }); 
+3
source share

All Articles