Synthetic Events in React
Key Concepts
- SyntheticEvent Object
- Event Pooling
- Common Synthetic Events
- Preventing Default Behavior
- Event Handlers
- Custom Synthetic Events
SyntheticEvent Object
The SyntheticEvent object is a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event, including stopPropagation() and preventDefault(), but works the same across all browsers.
Example:
function handleClick(event) { console.log(event.type); // Outputs: "click" } <button onClick={handleClick}>Click Me</button>
Event Pooling
SyntheticEvent is pooled, meaning that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. If you need to access the event properties after the event callback has been invoked, you should call event.persist().
Example:
function handleClick(event) { event.persist(); setTimeout(() => { console.log(event.type); // Outputs: "click" }, 1000); } <button onClick={handleClick}>Click Me</button>
Common Synthetic Events
React provides a set of common synthetic events that you can use to handle user interactions. Some of the most commonly used events include onClick, onChange, onSubmit, onKeyDown, and onMouseOver.
Example:
function handleChange(event) { console.log(event.target.value); } <input type="text" onChange={handleChange} />
Preventing Default Behavior
You can prevent the default behavior of an event by calling the preventDefault() method on the SyntheticEvent object. This is useful for stopping the default action of an event, such as preventing a form from submitting.
Example:
function handleSubmit(event) { event.preventDefault(); console.log('Form submitted'); } <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form>
Event Handlers
Event handlers are functions that are called in response to an event. In React, you can attach event handlers to elements using the onEventName syntax. The event handler will receive a SyntheticEvent object as its argument.
Example:
function handleKeyDown(event) { if (event.key === 'Enter') { console.log('Enter key pressed'); } } <input type="text" onKeyDown={handleKeyDown} />
Custom Synthetic Events
While React provides a set of common synthetic events, you can also create custom synthetic events using the EventEmitter pattern. This allows you to create and dispatch custom events that can be listened to by components.
Example:
import { EventEmitter } from 'events'; const eventEmitter = new EventEmitter(); function handleCustomEvent(data) { console.log(data); } eventEmitter.on('customEvent', handleCustomEvent); eventEmitter.emit('customEvent', 'Custom event triggered');
Analogies
Think of SyntheticEvent as a universal remote control that works with any TV. The remote (SyntheticEvent) has the same buttons (methods) regardless of the TV brand (browser), ensuring consistent behavior.
Another analogy is a shared bicycle. The bicycle (SyntheticEvent) is shared among multiple users (event callbacks), and after each use, it is reset (pooled) for the next user. If you need to keep the bicycle for longer, you can reserve it (persist).