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;
2
  • Dupe, check this, prob solves your doubts: stackoverflow.com/questions/42322553/… And also, regarding performance, this article is deff worth reading, will give you a lot of useful information if you're a React beginner: medium.com/@machnicki/… :) Commented Nov 10, 2017 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. Commented Nov 10, 2017 at 23:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.