How to get a onClick to work in a row - reactjs

Your problem is the function of user that creates the table row is not bound to your react component. The value of this will not be your react component and handleClick will not exist as a property of this.

Try

var users = this.state.users.map(function(user) {
  return (
    <tr onClick={this.handleClick}>
      <td>{user.name}</td>
      <td>{user.age}</td>
      <td></td>
    </tr>
  );}.bind(this);
});

Or use Underscore's bind if you want it to work on all browsers.


I'm new to react. How about this? You just wrap it in another function, then that function holds the closure scope and it calls it correctly.

No idea if this is bad practice or the performance difference, but it seems to work...

var users = this.state.users.map(function(user) {
  return (
    <tr onClick={()=>this.handleClick(user)}>
      <td>{user.name}</td>
      <td>{user.age}</td>
      <td></td>
    </tr>
  );}.bind(this);
});

Tags:

Reactjs