Cassidy
Cassidy

Reputation: 3365

Add class without state in React?

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.

Upvotes: 1

Views: 739

Answers (1)

dfsq
dfsq

Reputation: 193301

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')
  }
}

Upvotes: 4

Related Questions