Function onClick in the inside of a form is not working properly

Asked

Viewed 41 times

1

For some reason, the onClick function belonging to each of the images is not working properly... "index" should be the inside of the image itself, but React acts as if all the images had been clicked. Someone can help me?

hanldeClick(index){  
    var x;
    const newGames = this.state.games.slice();
    if(this.state.games[index].selected) {
        newGames[index].selected = false;
        x = -1;
    }
    else {
        newGames[index].selected = true;
        x = 1;
    }
    this.setState({games: newGames, selected: this.state.selected + x});
}   
renderGames(){
    var arr = [];
    const res = [];
    const len = this.state.games.length;
    var index = 0; 
    for(let i=0; i<Math.ceil(len/3); i++){
        for(let j=0; j<3; j++){
            if(index>=len)
                break;
            var style = this.state.games[index].selected ? "active" : "inactive";
            arr.push(
                <Col key={index}>
                    <img
                        onClick={()=>{this.hanldeClick(index)}}
                        className={style} 
                        src={this.state.games[index].image}
                        alt={this.state.games[index].description}
                    />
                </Col>
            );
            index++;
        }
        if(index<=len){
            res.push(<Row key={i} className='margin'>{arr}</Row>);
            arr = [];
        }
    }
    return res;
}

1 answer

0


The problem here is similar to what was asked here, is that when the onClick is called the value of index is another that what was in the loop iteration that created this component...

You can use the .bind to create a function that stores the arguments in memory for when it is called. Or declare local variables.

Example:

Instead of

onClick={()=>{this.hanldeClick(index)}}  

uses

onClick={this.hanldeClick.bind(this, index)}

Or:

const i = index;
arr.push(
    <Col key={i}>
        <img
            onClick={()=>{this.hanldeClick(i)}}
            className={style} 
            src={this.state.games[i].image}
            alt={this.state.games[i].description}
        />
    </Col>
);
  • Thank you very much! It worked :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.