jhamm jhamm - 3 months ago 68
React JSX Question

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

I am trying to get a click even to work with a table in

reactjs
. My first attempt was to make the whole row clickable. Here is my code:

var UserList = React.createClass({
getInitialState: function() {
return getUsers();
},
handleClick: function(e) {
console.log("clicked");
},
render: function() {
var users = this.state.users.map(function(user) {
return (
<tr onClick={this.handleClick}>
<td>{user.name}</td>
<td>{user.age}</td>
<td></td>
</tr>
);
});
return(
<div className="container">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Full Detail</th>
</tr>
</thead>
<tbody>
{users}
</tbody>
</table>
</div>
);
}
});


This did not work. I then tried to add a button in the table:

<button className="btn" onClick={this.handleClick}>Full Detail</button>


That also did not work. I have other
onClick
's working throughout my app, but how do I make this work with a table?

z5h z5h
Answer

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.

Comments