0

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?

fafrd
  • 1,017
  • 13
  • 17
  • you can fix this with .`bind()` as in `

    {thisLetter}

    `
    – WillD Apr 26 '20 at 04:50
  • That works. Also, the referenced duplicate question mentioned that I can use `let thisLetter` instead of `var thisLetter`, and that fixes the issue. (scoping in javascript is blowing my mind lol) – fafrd Apr 26 '20 at 04:55
  • Instead of binding you can use arrow functions for these simple cases. For using setTimeout or thing like that you need to bind the function so that this does not lose its scope. – Shaurya Vardhan Singh Apr 26 '20 at 06:02

0 Answers0