Seeing some weird behavior in my React code. The onClick event handler here is using the last value my variable was set to, rather than the current.
For example, here I have a function generateLetters
which creates elements like <p>a</p>
, <p>b</b>
, etc. I attach the function handleLetterClick
as the onClick event handler.
handleLetterClick(ltr) {
console.log("this letter: " + ltr);
}
generateLetters() {
var letters = [];
for (var i = 0; i < 26; i++) { // iterate through the alphabet
var thisLetter = (i+10).toString(36); // thisLetter = a, b, c...
letters.push(<p onClick={() => this.handleLetterClick(thisLetter)}>{thisLetter}</p>);
}
return letters;
}
This renders correctly:
<p>a</p>
<p>b</p>
<p>c</p>
...
<p>z</p>
BUT- the problem is the event handler always prints out this letter: z
! If I click on a or b, it prints z.
It seems like no matter how I construct this, the event handler uses the last-set value of thisLetter
.
What am I doing wrong here?
{thisLetter}
` – WillD Apr 26 '20 at 04:50