Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using react props in .map function [duplicate]

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?

like image 490
Paran0a Avatar asked May 11 '16 07:05

Paran0a


People also ask

What does .map do in React?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.

Should I have a unique key prop?

The "Each child in a list should have a unique "key" prop." warning happens in React when you create a list of elements without the special key attribute. Keys must be assigned to each element in a loop to give stable identity to elements in React. The key is used to correctly link the component to the DOM element.


2 Answers

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) => {
       /// ...
});
like image 107
Oleksandr T. Avatar answered Oct 12 '22 19:10

Oleksandr T.


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}
    />
  );
});
like image 23
Mauricio Poppe Avatar answered Oct 12 '22 20:10

Mauricio Poppe