Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log prop in React?

New to React, it's only my first day in class. All i'm trying to do, is when i click a box log the color prop.

I know i cant do console.log(this.props.color) because this is referencing App... this is all so confusing right now..any tips would be appreciated.



class Boxes extends Component{
  render(props){
    return (
      <div className="boxes" onClick={this.props.getBoxColor}>
        <div className="box1" color="red"></div>
        <div className="box2" color="orange"></div>
        <div className="box3" color="yellow"></div>
        <div className="box4" color="green"></div>
        <div className="box5" color="blue"></div>
      </div>
    );
  }
}

class App extends Component {

  getBoxColor=()=>{
    console.log(this.props)
  }


  render() {
    return (
    <Boxes classColor={this.color} getBoxColor={this.getBoxColor} />
    )
  }
}


ReactDOM.render(<App />, document.getElementById('root'));





1 Answers

Try this, tell me if it works for you.

class Box extends React.Component {
  render() {
    const className = this.props.className;
    const color = this.props.color;
    return (
      <div
        className={className}
        color={color}
        onClick={() => console.log(color)}
      />
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <Box className="box1" color="red" />
        <Box className="box2" color="blue" />
        <Box className="box3" color="green" />
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
like image 57
Nikita Malyschkin Avatar answered May 24 '26 10:05

Nikita Malyschkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!