Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we use anonymous function in event listener in react?

Tags:

reactjs

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;
like image 974
Alice Avatar asked May 10 '26 19:05

Alice


1 Answers

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.

like image 112
Steve Holgado Avatar answered May 14 '26 13:05

Steve Holgado