score:0

Make your state an array of colors like

this.state = {
  colors: [],
}

Then generate and push n randoms colors into it, iterate over the array and render the children

It will look something like this:

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      colors: []
    };
    this.setRandomColors = this.setRandomColors.bind(this);
  }

  generateRandomColor() {
    let randomColor = "rgb(";
    for (let i = 0; i < 3; i++) {
      randomColor += Math.floor(Math.random() * 255);
      if (i < 2) {
        randomColor += ",";
      }
    }
    randomColor += ")";
    return randomColor;
  }
  setRandomColors() {
    const colors = [];
    for (let i = 0; i < 3; i++) {
      colors.push(this.generateRandomColor());
    }
    this.setState(() => { return {colors: colors}; });
  }

  render() {
    return (
      <>
        {this.state.colors.map((color) => {
          return <ColorDiv color={color}></ColorDiv>;
        })}
        <button onClick={this.setRandomColors}>Press me!</button>
      </>
    );
  }
}

Related Query

More Query from same tag