0

Basically, I want to pass the value associated with span element to the function UpdateSelectedNumbers(). However, if I create an array of span elements using for loop the onClick eventhandler ( UpdateSelectedNumbers) is always called with value 9. This is not the case when i use the map function. Can someone explain why this happens

const stars = [1,2,3,4,5,6,7,8,9];
var temp = [];
for(var i=0;i<9;i++){
    temp.push(<span className={getClass(i+1)} onClick={()=>props.UpdateSelectedNumbers(i+1)}>{i+1} </span>)
}
return (
     <div>
     {stars.map(x => <span className={getClass(x)} onClick={()=> props.UpdateSelectedNumbers(x)}>{x}</span>)}
     {temp}
     </div>
    )
imjared
  • 19,492
  • 4
  • 49
  • 72
jayasurya_j
  • 1,519
  • 1
  • 15
  • 22
  • 1
    Use `let` instead of `var` for `i`. [Why this works is explained in detail here](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav). – Tholle Jul 14 '18 at 16:49
  • 1
    Thanks scoping was the mistake – jayasurya_j Jul 14 '18 at 17:14

1 Answers1

0

Because var is scoped to the nearest function, all your ()=>props.UpdateSelectedNumbers(i+1) functions will get the final value of i, which is 8.

You could instead use let which is scoped to the nearest enclosing block, so each iteration of the loop will have its own value.

Tholle
  • 108,070
  • 19
  • 198
  • 189