mardi 10 décembre 2019

How to create a different random number for every single div with React on onclick event?

I would like to get a different random number for every single div every time that I click on the image. At the moment, I am receiving the same random number for all div elements and I have no idea, how I could separate it. I would appreciate any Idea. Thanks.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      randomNumber: 0
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
     const min = 0;
     const max = 9;
     const randFloorNumber = Math.floor(min + Math.random() * (max - min));

     this.setState({
       randomNumber: randFloorNumber
     });
   }

  render() {

    const divs = [1, 2, 3, 4, 5, 6, 7];
    let div = divs.map( div =>
        <div key={divs.div} className="App-number-div col border border-info">
           {this.state.randomNumber}
        </div>
    );

    return (
      <div className="App">
        <img src={logo} alt="Logo" onClick={this.handleClick} />
        <div className="container">
          {div}
        </div>
      </div>
    );
  }
}



Aucun commentaire:

Enregistrer un commentaire