Introduction
An event is a triggered action that occurs due to a user action or a system-generated event. Pressing a key, mouse click, a web page loading, window resizing, and other interactions are examples of events.
We wouldn't be able to construct awesome responsive web applications that respond to a user's every touch without event handlers in React or any other framework for that matter.
Event handling is essential because it ensures that React keeps track of each action taken by the user. React has its event handling system that works similarly to how DOM elements handle events.
In this article, we’ll be discussing synthetic events in React. So, let’s get started!
Also See, Dropdown in React JS, Hooks in React JS
Synthetic Events
React uses a synthetic events system to ensure that React apps and interfaces are consistent and fast. It provides consistency by normalizing events across browsers and systems so that they have the same properties.
With the help of an example, we are aware of the onclick event that occurs when the user clicks on an element. So, that onClick event does not exist in a Windows or Android app.
That code will not work if we use a native onClick event. When we compile our React code, it can replace reactOnClick with native click events for any platform. Provided we abstract it behind another function like reactOnClick.
Synthetic events have allowed react to run in Electron for mobile apps and react native for iOS and Android.
Furthermore, because a single native event can generate multiple synthetic events, it allows you to create new ones quickly.
For example, a syntheticTap event could be emitted if you receive a native touchStart then a native touchEnd in succession.
function Form() {
function handleSubmit(e) {
e.preventdefault();
console.log("Hey, you hit submit");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Here, e is a synthetic event. React defines these synthetic events according to the W3C spec so, we don't have to worry about cross-browser compatibility.
One important point to note here is that:
- The synthetic events are distinct from the browser's native events and do not map directly to them. Abstraction is the term for this type of pattern. We can inject multiple implementations based on what we're writing by separating the code we write from how it runs.
For example, OnMouseLeave event.nativeEvent, will point to a mouseout event. The mapping is not part of the public API and is subject to change at any time.
The attributes of a synthetic event object are as follows:
- boolean bubbles
- boolean cancelable
- boolean defaultPrevented
- boolean isDefaultPrevented()
- boolean isTrusted
- boolean isPropagationStopped()
- DOMEventTarget target
- DOMEventTarget currentTarget
- DOMEvent nativeEvent
- number eventPhase
- number timeStamp
- string type
- void preventDefault()
- void stopPropagation()
- void persist()