I try to trigger an onClick event in a map function, and I get this error :
TypeError: Cannot read property 'handleClick' of undefined
How do we trigger an onClick event in a map function ?
Here is my code :
class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState((prevState) => ({
isToggleOn: !prevState.isToggleOn,
}));
}
render() {
if (this.props.data) {
var recipes = this.props.data.map(function (recipe, i) {
return (
<div
key={i}
className="col-8 offset-col-1 f-l relative m-t-10"
>
<div className="col-6 f-l">
<p className="col-8 f-l">{recipe.title}</p>
<button className="f-l" onClick={this.handleClick}>
Voir la recette
</button>
</div>
</div>
);
});
}
return (
<div className="RecipeList">
<div className="col-12">
{recipes}
<div className="both"></div>
</div>
</div>
);
}
}
thispoints to the map function where nohandleClickfunction definition exists. You need to instantiate a variable withthisoutside themapand use it inside your map