Sunday, 10 April 2016

javascript - Using react props in .map function




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:






Child:



(I'm using ES6 classes)




render() {  
var RequestNodes = this.props.data.map(function(request) {
return (
key={request.TID}
changeTid={this.props.changeTid}
/>
);
});


return (
{RequestNodes}

);
}


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?


Answer



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) => {
/// ...
});


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...