Using synthetic event objects
When you attach an event handler function to a DOM element using the native addEventListener()
function, the callback will get an event argument passed to it. Event handler functions in React are also passed an event argument, but it's not the standard Event instance. It's called SyntheticEvent
, and it's a simple wrapper for native event instances.
Synthetic events serve two purposes in React:
- They provide a consistent event interface, normalizing browser inconsistencies.
- They contain information that's necessary for propagation to work.
Here's a diagram of the synthetic event in the context of a React component:
When a DOM element that is part of a React component dispatches an event, React will handle the event because it sets up its own listeners for them. Then, it will either create a new synthetic event or reuse...