Event handling is very important in React as it helps to respond to user actions. Events can be clicking a button or changing the text box. However, React handles events in a different way.
Events in React are known as synthetic events. The synthetic event is a cross-browser wrapper of the browser’s native event. It works exactly in the same way in each browser.
Let’s take an example of an HTML handling event on button click :
This click event is slightly different in React, the event name is written in camel case instead of lowercase :
Also, we cannot pass return false to prevent the default behavior of the event. We have to explicitly use preventDefault().
The event handling in-class component is a bit different from event handling in the function component. As we use ES6 classes to define class components. In classes methods are not bound by default, we have to bind the event handling function so that it can be called.
We can bind the method in the constructor itself.
If you do not want to bind methods in the constructor in this way, you can do the public class field syntax to write the function.
You can also use the arrow function syntax on the event. In the below example we have used the arrow function syntax when calling the method onClick event.
Subscribe to our Youtube channel for more videos :