18

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

Parent:

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

Child:

(I'm 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 can't use this.props.changeTid in my map function as this is not referencing what I wan't. Where do I bind it so I can access my props?

Paran0a
  • 3,359
  • 3
  • 23
  • 48

2 Answers2

30

You can set this for .map callback through second argument

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

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

var RequestNodes = this.props.data.map((request) => {
       /// ...
});
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
5

If you're using ES6 you can use arrow functions which doesn't bind its own this

var RequestNodes = this.props.data.map(request => {
  return (
    <Request 
        key={request.TID} 
        changeTid={this.props.changeTid}
    />
  );
});
Mauricio Poppe
  • 4,817
  • 1
  • 22
  • 30