Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Js click event within a for loop [duplicate]

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="#">{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.

like image 641
Genarito Avatar asked Dec 27 '16 04:12

Genarito


1 Answers

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="#">{index}</a>
    </li>
)
like image 68
Andy Ray Avatar answered Oct 20 '22 04:10

Andy Ray