Alex
Alex

Reputation: 646

Handle event in all nested HTML elements in ReactJS

While building a table, I'm binding onClick handler to td element:

<td data-person-id={person.id} onClick={this.removePerson}>
    <button type="button" className="btn btn-default btn-default">
        <span className="glyphicon glyphicon-remove" aria-hidden="true">Remove</span>
    </button>
</td>

But when an event is handled, it points to button or span elements but not td one so it means I can't just get needed data-person-id attribute. How can I fix it?

Full code https://jsfiddle.net/osqbvuub/1/

Thank you.

Upvotes: 0

Views: 54

Answers (1)

Rafael Quintanilha
Rafael Quintanilha

Reputation: 1432

<td>
    <button 
      type="button" 
      className="btn btn-default btn-default"
      onClick={this.removePerson.bind(this, person.id)}>
        <span className="glyphicon glyphicon-remove" aria-hidden="true">Remove</span>
    </button>
</td>

Let your button element handle onClick (otherwise you might have weird behavior like clicking outside of the button but inside of td triggering an event) and bind the id to the context.

Then, later on your removePerson function access id directly:

...
removePerson(id) {
  // do stuff
}
...

Upvotes: 2

Related Questions