0

So i'm having an issue understanding the difference in the manner I make a function call to a prop I passed to a child component.

onClick(id)   {
    console.log(id)
}

<div className="card" onClick={() => this.props.onClick(this.state.id)}>

v.s.

<div className="card" onClick={this.props.onClick(this.state.id)}>

The first works as expected and gives me the id of the components state when it is clicked. The second one upon loads prints all of the id's for every component before I even get a chance to click on them. What am I missing? onClick is onClick, why is that return statement so important. Thank you for your help.

Brian Adams
  • 43,011
  • 9
  • 113
  • 111

3 Answers3

0

You must be calling onClick as

   onClick={this.props.onClick(this.state.id)}

So change to

  onClick={() => this.props.onClick(this.state.id)}

This will prevent getting event handler function called automatically. With the above change the onClick event handler function gets called only when you click

Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
0

onClick in <div> expects a function, which is what you give at #1 (called arrow function).

At #2 you give result of executing this.props.onClick(this.state.id) which is void.

SLCH000
  • 1,821
  • 2
  • 14
  • 15
0

onClick needs to be passed a function.

Your first example passes onClick a function that calls this.props.onClick(this.state.id) when it runs and works properly.

Your second example passes onClick the result of evaluating this.props.onClick(this.state.id) which is why all of the id's are printed immediately when the component loads. I'm guessing that nothing is returned from calling this.props.onClick(this.state.id) so onClick has nothing to call when the div does get clicked.

Brian Adams
  • 43,011
  • 9
  • 113
  • 111