React Js click event within a for loop

All we need is an easy explanation of the problem, so here it is.

I’m working with React. This is my code:

var rows = [];
for(var i = 1; i <= this.state.numberOfPages; i++) {
    rows.push(<li key={i.toString()} onClick={() => this.getResults(i)}><a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">{i}</a></li>)
};

getResults() function is as simple as:

getResults: function(page = this.state.currentPage) {
    console.log(page);
},

this.state.numberOfPages is equal to 3. The issue is that, when I click on <li> tags, 4 is always showed in console. However <li> values are showed correctly in the HTML. I can’t understand why is always being evaluated the last i value when it is passed by parameter.

A detail:

In React Console, key property are correct too. The problem is with the parameter only.

Thanks in advance and sorry about my English.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

As mentioned in the duplicated answer, you need to close over the variable with some inner function. Using map is an easy way to achieve this:

var rows = new Array(this.state.numberOfPages).fill(0).map( ( zero, index ) =>
    <li key={index} onClick={() => this.getResults(index)}>
        <a href="#" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">{index}</a>
    </li>
)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply