Ad

React OnClick Events In Loops

- 1 answer

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!

Ad

Answer

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

Ad
source: stackoverflow.com
Ad