user10638072
user10638072

Reputation:

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'));




Upvotes: 3

Views: 659

Answers (1)

Nikita Malyschkin
Nikita Malyschkin

Reputation: 692

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"));

Upvotes: 2

Related Questions