1

I have a React app with a table (with a variable number of rows). I want to be able to click a link or button in one cell of the table to add a class to the parent of that link/button.

Here's an example row in the table:

<tr>
  <td>Sample</td>
  <td className="num">40%</td>
  <td><a>Accept</a></td>
</tr>

When I click "Accept", I want num (or the whole tr, if that's easier) to have a new class added. How can I do this? Because I have a variable number of rows I want to avoid using state.

1 Answer 1

4

You could delegate click event to the table, this way you will have only one event handler for entire table:

<table onClick={this.onClick}>

Then have something like this for onClick method:

onClick(e) {
  if (e.target.tagName === 'A') {
    const tr = e.target.parentNode.parentNode
    tr.classList.toggle('selected')
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.