Why we use synthetic events in ReactJS ?
In ReactJS, there are events by which user uses to interact with an application UI. React listens to events at the document level, after receiving events from the browser, React wraps these events with a wrapper that has a similar interface as the local browser event, which helps us to use methods like preventDefault().
Why use such a wrapper?
So, often we use different browsers where the same event has different names. Here wrapper does is triggering all the different names for the same event effect. Therefore, whenever we are triggering an event in a ReactJS, we are not actually trying to trigger the real DOM event, instead, we are using the ReactJS custom event type, which is the synthetic event.
The examples of the synthetic events are onClick(), onBlur() and onChange(). These all are not real DOM events but react synthetic events.
Benefits of using synthetic events:
- Cross browsers applications are easy to implement.
- Synthetic events are that ReactJS reuses these events objects, by pooling them, which increase the performance.
Let’s look at an example of a ReactJS application using synthetic events.
Creating React Application
Step 1: Create a React application using the following command:
npx create-react-app example
Step 2: After creating your project folder i.e. example, move to it using the following command:
Project structure: It will look like this.
Example: Write down the following code in the index.js and App.js files.
Step to run the application: Run the application using the following command:
Output: The alert event is wrapped with onClick synthetic event.
This way we use synthetic events a lot in our application based on ReactJS.
Please Login to comment...