Ways to attach event handler to OnClick in React

Hi Guys,

So I get really confused about how to attach onClick handlers in React. Now I see 2 ways to attach handlers:

<MoreVertIcon onClick={this.toggle3DotsModal}/>
<MoreVertIcon onClick={() => this.toggle3DotsModal}/>

What’s the reasoning behind using one over the other?

The second one should be onClick={() => this.toggle3DotsModal()}.

You generally use second version if you need to pass some parameters to the function.

1 Like

That’s the only difference?

One thing to be considered when choosing between these two options is that event object will be passed to your handler on click, so if your handler expects this as the first argument and doesn’t need any other parameters, then there is no reason to additionally wrap it into a function. If you have custom handler and you need to pass extra arguments, then it is the way to go:

onClick={(e) => this.toggle3DotsModal(e, this.state, this.setState)}

In this :point_up: example we’re additionally passing component’s state and setState handler to avoid unnecessary this-binding of the toggle3DotsModal method.

1 Like