Faalsh Faalsh - 2 months ago 21
React JSX Question

React onClick Event Not Working

I'm trying to make the onClick event working in React but with no luck. I cannot figure out what is wronge

var Item = React.createClass({
render: function(){
return <div>{this.props.text}</div>;
}
});

var ItemList= React.createClass({
handleClick: function(i){
console.log("clicked",i)
},
renderListItems: function() {
var list = [];
for (var i = 0; i < 9; i++) {
var text = "item " + i;
list.push( <Item key={i} text={text} onClick={this.handleClick.bind(this,i)} /> )

}
return list;
},

render: function() {

return (
<div>
{
this.renderListItems()
}
</div>
)
}});


ReactDOM.render(
<ItemList />,
document.getElementById('container')
);


Any idea why it is not working ?

Here is a demo for the code above https://jsfiddle.net/69z2wepo/55485/

Answer

You need to pass your onClick handler through to the div in your Item component:

var Item = React.createClass({
  render: function(){
    return <div onClick={this.props.onClick}>{this.props.text}</div>;
  }
});