FabZbi
FabZbi

Reputation: 538

React onClick Events in loops

Im trying to bind some variables to a onClick event inside a React Component. Im doing this from within a for loop because I need many of them.

My code looks like this:

generateCells(pieData){
        var cells = []

        for(var j = 0; j < pieData.length; j++){
            var imageIndex = pieData[j].image;
            var image = [pieData[j].innerIndex, pieData[j].angle];
            console.log(image);
            var rowLength = pieData.length;
            cells.push(<Cell key={imageIndex} onClick={() => this.retake(image, rowLength)} fill={this.state.progressState[imageIndex] ? '#00C49F' : '#FF8042'}/>)
        }

        return cells;
    }

But my image variable in the onClick event is always from the last iteration of the loop. How is this possible?

Thanks for any advice!

Upvotes: 2

Views: 742

Answers (3)

Shubham Verma
Shubham Verma

Reputation: 5054

Change var to let in for loop. let create new binding and let creates a variable declaration for each loop which is a block-level declaration. while var scoped to the global scope so by the time you click var value is attached to the global scope and displaying last value:

for(let j = 0; j < pieData.length; j++){
            var imageIndex = pieData[j].image;
            var image = [pieData[j].innerIndex, pieData[j].angle];
            console.log(image);
            var rowLength = pieData.length;
            cells.push(<Cell key={imageIndex} onClick={() => this.retake(image, rowLength)} fill={this.state.progressState[imageIndex] ? '#00C49F' : '#FF8042'}/>)
        }

        return cells;


Demo : https://stackblitz.com/edit/react-geu71r

Upvotes: 1

Arthur
Arthur

Reputation: 5148

This is because you're using var and it's creating a variable scoped into you're generateCells() function. Try with let to see the difference (the variable scope will be the for loop)

I did a Codepen some time ago to view the difference between them, this may help you: https://codepen.io/ArthyFiciel/pen/rxKeQR

Upvotes: 4

Dominik Matis
Dominik Matis

Reputation: 2146

Change var to let infor loop, this should help

Upvotes: 0

Related Questions