Reputation: 39
I am trying to map through an array and create links which will update state. When I map through the array and create the links I get :
TypeError: Cannot read property 'handleClick' of undefined
var FilterList = React.createClass({
handleClick : function(e, list){
this.props.callbackFromParent(list);
this.setState({showing : list});
},
render: function() {
if(this.props.sdata ){
var seasons ='';
seasons = this.props.sdata.Seasons.map(function(season, i) {
if(i < 30) {
var playkey = season.mediaId;
var name = season.Season;
return (
<li> <a href="#" onClick={(e) => this.handleClick(e, {playkey})}>{name}</a></li>
);
}else{
return (<div key={playkey}></div>);
}
});
return (
<Row className="singleChannelSeasonsList">
<Grid>
<Col md={12}>
<ul className="seasons">
{seasons}
</ul>
</Col>
</Grid>
</Row>
);
} else {
return (
<Row className="singleChannelSeasonsList">
<Grid>
<Col md={12}>
<ul className="seasons">
<li><a href="#" className="activeItem" onClick={(e) => this.handleClick(e, "list")}>All</a></li>
<li> <a href="#" onClick={(e) => this.handleClick(e, "category/Entertainment")}>Entertainment</a></li>
<li><a href="#" onClick={(e) => this.handleClick(e, "category/Health%20&%20Wellness")}>Health & Wellness</a></li>
<li> <a href="#" onClick={(e) => this.handleClick(e, "category/Opinion")}>Opinion</a></li>
</ul>
</Col>
</Grid>
</Row>
);
}
}
});
export default FilterList;
How can I map through the data and generate the handleclick links. {this} is bound and it works when i dont have this.props.sdata. Thanks!
Upvotes: 0
Views: 436
Reputation: 116
The problem is the value of "this" keyword is determined by how a function get called. "this" is called inside of anonymous function in "map()". So "this" will be undefined.
Solution:
this.props.sdata.Seasons.map(function(season, i) {
//....blah blah blah
}.bind(this));
this.props.sdata.Seasons.map(function(season, i) {
//....blah blah blah
},this);
Upvotes: 1
Reputation: 488
If I understand your question correctly, you need to bind this to your event handler:
...
onClick={this.handleClick.bind(this)}
...
Upvotes: 0
Reputation: 2242
You haven't bound {this} to this.props.sdata.Seasons.map( () => {} )
yet!
It should be:
render: function() {
if(this.props.sdata ){
var seasons ='';
seasons = this.props.sdata.Seasons.map( (season, i) => {
//...
});
} else {
//...
}
//...
}
Upvotes: 0