Middle+
What is event handling in React? What is a synthetic event?
sobes.tech AI
Answer from AI
In React, event handling is a mechanism by which components respond to user actions (such as clicks, text input, mouse hover). Instead of directly attaching handlers through the DOM, React uses its own event system called Synthetic Events.
A Synthetic Event is a wrapper around the native browser event, implemented in React. It provides cross-browser compatibility and a unified interface for working with events. Synthetic events have the same properties and methods as native events but are additionally optimized for performance and lifecycle management.
Example of handling a click in React:
function Button() {
function handleClick(event) {
console.log('Button clicked', event);
}
return <button onClick={handleClick}>Click me</button>;
}
Here, onClick is a prop that takes an event handler function, and event is a synthetic event.