john doe john doe - 1 month ago 6
React JSX Question

Passing dynamic argument on onClick inside for does not work

Following react code does not work.'select' function is always called with 10 instead of assigned values.

select( x ) {
alert( x ); // Always alerts 10.
}

render() {
var AllData = [];
for( var i = 0; i<10 ;i++ ) {
AllData.push(
<div key={i} onClick={() => this.select(i)} >{i}</div>
);
}
return (
<div>
{AllData}
</div>
);
}


How do I pass dynamic value in for loop correctly?

Answer

Since you are using ES2015 arrow function notation, I'd suggest to just replace var by let for your loop variable initialization. That way you have a true block scope, otherwise you have to deal with function scope which is the root of your trouble here.

for( let i = 0; i<10 ;i++ ) {
   AllData.push( 
       <div key={i} onClick={() => this.select(i)} >{i}</div>
   );
}