I am new to react, so I don't know much about it. I am trying to add a click handler to a li but the function seems to be undefined?
var ActivityList = React.createClass({
getInitialState: function() {
return {name:"test"};
},
handleClick:function(e){
console.log(e.target.name);
},
render:function(){
return (
<ul>
{this.props.data.map(function(game){
return <li onClick={this.handleClick} name={game.name}>{game.name}</li>;
})
}
</ul>);
}
});
I am wondering if it is because i have my scoping wrong here?
The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.
Adding EventsReact events are written in camelCase syntax: onClick instead of onclick . React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()" .
This is because when you use an arrow function, the event handler is automatically bound to the component instance so you don't need to bind it in the constructor. When you use an arrow function you are binding this lexically.
Set this
to .map
, because in .map
callback this
refers to global scope(in browser it is window
or undefined
if you use strict mode
)
this.props.data.map(function(game) {
return <li onClick={this.handleClick} name={game.name}>{game.name}</li>;
}, this);
^^^^^
Example
You can also use an arrow function to avoid binding this
in the function at all:
this.props.data.map(game =>
<li onClick={this.handleClick} name={game.name}>{game.name}</li>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With