Event Handler
Learn how to define event handlers in a React app. You will also get to learn the importance of using Arrow function inside event handlers.
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.
...<buttononClick={() => 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:
...<buttononClick={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. ...