Search⌘ K

Event Handler

Explore how to implement event handlers in React class components, focusing on passing parameters through arrow functions. Understand the importance of function references in event handlers, how to avoid immediate execution, and the impact on app performance. Learn to use higher-order functions and ES6 arrow syntax to manage event-driven actions within your React app.

We'll cover the following...

Now we’ll cover event handlers in elements. In the application that you are building, you are using the following button element to dismiss an item from the list.

Javascript (babel-node)
...
<button
onClick={() => this.onDismiss(item.objectID)}
type="button"
>
Dismiss
</button>
...

This function is already complex because it passes a value to the class method and has to wrap it in another (arrow) function. Essentially, it has to be a function that is passed to the event handler. The code given below wouldn’t work if you are following along on a local React setup, because the class method would be executed immediately when you open the application in the browser:

Javascript (babel-node)
...
<button
onClick={this.onDismiss(item.objectID)}
type="button"
>
Dismiss
</button>
...

onClick

When using onClick={doSomething()}, the doSomething() function executes immediately when the application is opened in a browser. ...