Bonnie
Bonnie

Reputation: 33

How to give unique id to table rows in react

I need to give different IDs to table rows, so that when I click on the first row, it'll show "selectedRow: 1" on console. Click on the second row, it'll show "selectedRow: 2"

Thanks in advance!

Here's my code:

<tbody>
  {this.testData.map((item, i) => {
    return (
      <tr onClick={this.handler} key={i} >
        <td>{item.name}</td>
        <td>{item.age}</td>
        <td>{item.address}</td>
      </tr>
    );
  })}
</tbody>

handler=(e)=>{
  let selectedRow = e.target.id //doesn't work
  console.log("selectedRow:", selectedRow)
}

Upvotes: 0

Views: 4909

Answers (2)

Josna battula
Josna battula

Reputation: 9

For the tr onClick we can give our id as we like like <tr onClick={this.handler(item.id)}> and our handler function will be high level function like below, then we don't require to create function each time

handler = id => e => {
console.log(id)

}

Sample code code from sandbox

Upvotes: 0

SoKeT
SoKeT

Reputation: 610

For that to work you would need to give every tr an id attribute, but it would be better if you just straight up pass that id to the function, like so:

<tr onClick={() => this.handler(item.id)}>

You can also use the index if the items don't have unique IDs.

Now the handler function would receive the id as an argument:

handler = (selectedRow) => {
    console.log("selectedRow:", selectedRow)
}

Upvotes: 2

Related Questions