0

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.

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>
    );
  }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
pilar torres
  • 1
  • 1
  • 1
  • Since you are only using the number inside the generated divs, couldn't you return the random number instead of setting the state, and call the function on each iteration? `{getRandomNumber()}` – Dupocas Dec 10 '19 at 13:12

2 Answers2

0

An alternative for generate a random number is using Date.now().

So, instead of:

const randFloorNumber = Math.floor(min + Math.random() * (max - min));

Use:

const randFloorNumber = Date.now();

By using Date.now(), you'll get the timestamp of the Date object - as is show in this answer.

0

Everytime you are setting the state, you are setting just one random number in your state.

That means, your render method is being executed again. You need one random number in the state for each div.

A possible solution would be:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      amount: 7,
      randoms: []
    };

  }

  componentDidMount() {
      this.handleClick();
  }

  handleClick = () => {
    const min = 0;
    const max = 9;
    const randoms = []; 

    for (let i = 0; i < this.state.amount; i++) {
        const randFloorNumber = Math.floor(min + Math.random() * (max - min));
        randoms.push(randFloorNumber);
    }
        this.setState({randoms})
  }

  render() {
    const randoms = this.state.randoms.map(random => {
        return (
        <div key={idx} className="App-number-div col border border-info">
            {random}
        </div>
        )
    })

    return (
      <div className="App">
        <img src={logo} alt="Logo" onClick={this.handleClick} />
        <div className="container">{randoms}</div>
      </div>
    );
  }
}
Maximiliano Poggio
  • 1,162
  • 10
  • 23