3

I am a React beginner. While learning React, sometimes I see people use anonymous functions in event listeners, I wonder if the below codes are the same. I think, to call function onDelete, we only need to use onClick={this.onDelete(id)}

    const cartItem=this.props.cart.map((bookCart)=>{
                return (    
    <Button onClick={()=>{this.onDelete(bookCart._id)}}>Delete</Button>
    )
},this;

and

    const cartItem=this.props.cart.map((bookCart)=>{
                return (    
    <Button onClick={this.onDelete(bookCart._id)}>Delete</Button>
    )
},this;
Alice
  • 281
  • 1
  • 3
  • 20
  • Dupe, check this, prob solves your doubts: https://stackoverflow.com/questions/42322553/when-to-use-anonymous-functions-in-jsx And also, regarding performance, this article is deff worth reading, will give you a lot of useful information if you're a React beginner: https://medium.com/@machnicki/handle-events-in-react-with-arrow-functions-ede88184bbb :) – elbecita Nov 10 '17 at 22:54
  • Actually, your second example won't work since you're calling the function instead of just passing it. You have to use an arrow function or bind the arg. – Rick Jolly Nov 10 '17 at 23:13

1 Answers1

7

You can use an arrow function when you need to pass arguments.

If you add parentheses to the function you are actually executing the function.

Therefore, with this code:

<Button onClick={ this.onDelete(bookCart._id) }>Delete</Button>

...you are setting onClick to the result of this.onDelete(bookCart._id)

If you use an arrow function like this:

<Button onClick={ () => this.onDelete(bookCart._id) }>Delete</Button>

...then you are setting onClick to a function that, when executed, will call this.onDelete with the parameters.

I hope this helps.

Steve Holgado
  • 11,508
  • 3
  • 24
  • 32