Union find
Union find

Reputation: 8150

React {this.state.xyz} inside this.props.data.map

I want to pass a state to a component inside a this.props.data.map. But I'm throwing an error.

Here is the setup:

var PortraitNodes = this.props.data.map(function (image, i) {
                return (
                    <div className="portrait" key={i} >
                        <PortraitPhoto 
                          imagepath={image.id} />
                        <PortraitSpeaker 
                          isPlaying={this.state.isPlaying}
                          whichPlaying={this.state.whichPlaying}
                          onToggle={this.playerAction} />
                        <PortraitName 
                          names={image.name} 
                          title={image.title} />
                   </div>
                  );

It would appear as though the this is accessing the map function.

What is the workaround here?

Upvotes: 0

Views: 504

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47172

You need to bind the function that map utilizes to the instance of your component in order to be able to access the state.

this.props.data.map(function (){}.bind(this));

You can also pass this as an argument to map

.map(function (){}, this);

Upvotes: 2

Related Questions