dimanche 14 mars 2021

How can i pass different props to more than one children component from the parent one in React?

Im working on a color palette generator in React, and the problem i have is that when i try to pass different colors to every one of the child divs that will form the color palette every one gets the same color.

Here is the code

    class ColorPaletteContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: null,
    };
    this.setRandomColor = this.setRandomColor.bind(this);
  }

  setRandomColor() {
    let randomColor = "rgb(";
    for (let i = 0; i < 3; i++) {
      randomColor += Math.floor(Math.random() * 255);
      if (i < 2) {
        randomColor += ",";
      }
    }
    randomColor += ")";
    this.setState({
      color: randomColor,
    });
  }

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

class ColorDiv extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1 style=>This is a color div!</h1>
      </div>
    );
  }
}

Basically the parent component passes the same color to all the 3 child components, because im passing the same state. Any idea of how i can pass different colors?




Aucun commentaire:

Enregistrer un commentaire