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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With