Skip to content
doubtly

1 answer

Answer: In React, a synthetic event is React's own cross-browser wrapper object (SyntheticEvent) around the browser's native event, giving every event handler the same interface in all browsers.

Explanation:

  • When you write a handler such as onClick={handleClick}, React does not pass the raw DOM event to the handler. It passes a SyntheticEvent object built from the native event.
  • Different browsers expose events with small differences (property names, behaviour). The synthetic event normalises these, so the same code works in Chrome, Firefox, Safari, etc.
  • It has the same interface as a native event, including preventDefault(), stopPropagation(), target, currentTarget, type and timeStamp.
  • The original browser event is still available through e.nativeEvent if it is needed.
  • React uses event delegation: instead of attaching a listener to every element, it attaches listeners at the root of the app and dispatches synthetic events to the right components. This saves memory and handles dynamically added elements.
  • Event names are written in camelCase (onClick, onChange, onSubmit) and a function is passed instead of a string.
  • In React 16 and earlier the event objects were pooled (reused), so their properties were cleared after the handler ran; since React 17 pooling is removed and the object can be used later safely.

Example:

function SignupForm() {
  function handleSubmit(e) {
    e.preventDefault();          // stops the page reload
    console.log(e.type);         // "submit"
  }
  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Save</button>
    </form>
  );
}

Here e is a SyntheticEvent; calling e.preventDefault() works the same way in every browser.

codelikepro · 19 Aug 2022 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.