0

How to retrieve the inside of my tag on click

I have tried something like this at the creation of the element but the value of i is always equal to the last value in onClick.

heads = ['alligator', 'snake', 'lizard'];
for (var i = 0; i < size;i++){
    tHead.push(<th onClick={() => this.handleRowClick(heads[i])}> {heads[i]} </th>);
}
Prashant Patel
  • 1,087
  • 11
  • 18
silverspy
  • 3
  • 4

1 Answers1

0

try:

heads.forEach((head)=>{
    tHead.push(<th onClick={() => this.handleRowClick(head)> {head} </th>});
}

The advantage of using forEach over a for loop is that the index and value are bound to a specific loop iteration instead of the surrounding scope. Thus when the loop index changes the closures keep the old loop-index.

This will also work:

heads.forEach((_, index)=>{
    tHead.push(<th onClick={() => this.handleRowClick(heads[index])> {heads[index]} </th>});
}

or this:

for (var i = 0; i < size;i++){
    let j = i;
    tHead.push(<th onClick={() => this.handleRowClick(heads[j])}> {heads[j]} </th>);
}

The last one works because j is bound to a specific loop iteration, so it will not change while i will.

mousetail
  • 7,009
  • 4
  • 25
  • 45