Reputation: 1121
I'm trying to pass the 'handleItemClick' function from the 'Dropdown' component, down to they 'Team' component, however, I can't get it past the 'List' component. The strange thing is, is that when I log the props inside the 'List' it says that 'itemClick' is in the 'this.props' object and yet when I set it as a prop on the 'Team' component it says "Cannot read property 'itemClick' of undefined".
Any help would be much appreciated.
Dropdown Component:
var Dropdown = React.createClass({
getInitialState: function(){
return {
display: false
};
},
handleClick: function(e){
this.setState({display: !this.state.display})
},
handleItemClick: function(e){
console.log("Something");
},
render: function(){
return (
<div className="dropdown">
<Button whenClicked={this.handleClick} className="btn-default" title={this.props.data.title} number={this.props.data.teams.length} />
<List teams={this.props.data.teams} display={this.state.display} itemClick={this.handleItemClick}/>
</div>
);
}
});
List Component:
var List = React.createClass({
render: function(){
console.log(this.props)
var teams = this.props.teams.map(function(team){
return <Team key={team} team={team} teamChoice={this.props.itemClick} />
});
var displayStyle = {
display: this.props.display ? 'block' : 'none'
};
return (
<ul style={displayStyle} className="dropdown-menu">
{teams}
</ul>
);
}
});
Upvotes: 1
Views: 4762
Reputation: 6427
Kristofen44 was close:
Array.prototype.map()
loses the this
from your parent scope inside it's callback. But the function includes a variable input for accessing this
within it:
var teams = this.props.teams.map(function(team){
return <Team key={team} team={team} teamChoice={this.props.itemClick} />
}, this);
Upvotes: 5
Reputation: 118
I'm not sure but I think the error resides in List Component's render function when you map team to generate nodes. the map callback function loses the context 'this'. I think you have to bind the callback function to 'this' explicitly. Like so :
var teams = this.props.teams.map(function(team){
return <Team key={team} team={team} teamChoice={this.props.itemClick} />
}.bind(this)); // <------
BTW, being quite new to react, I don't know if it's good practice to pass an whole object to the attribute 'key' of your Team component... I wonder if it's not better to just pass an id or something like that..
Hope it helps
Upvotes: 1