SyntheticEvent — onChange/onSubmit Types and When to Call preventDefault
SyntheticEvent — onChange/onSubmit Types and When to Call preventDefault
💡 Why Learn This? — You Use It Every Day Yet Guess at the Types
5 Core React Event Types
1. SyntheticEvent — A Wrapper Around the Browser Event
React events are a wrapper built on top of the standard Event, adding cross-browser compatibility, pooling, and delegation.
2. The 5 Signatures You'll Use Most
3. target vs currentTarget
Clicking the span gives e.target = span, e.currentTarget = button. Use currentTarget when you need the exact type of the element the handler is attached to.
4. preventDefault — When to Call It
5. For checkboxes, use checked, not value
6. Event Delegation — React Handles It for You
Even though you write <button onClick={...}>, React attaches only one listener to the root container and walks up the virtual tree to invoke handlers. You don't need to think about this detail.
💡 💡 5 React Event Practical Tips
1. Memorize just these 5
- ▸onChange for input/textarea/select:
ChangeEvent<HTMLInputElement>, etc. - ▸onSubmit for form:
FormEvent<HTMLFormElement> - ▸onClick for button:
MouseEvent<HTMLButtonElement> - ▸onKeyDown for input:
KeyboardEvent<HTMLInputElement> - ▸focus/blur:
FocusEvent<HTMLInputElement>
2. Always call e.preventDefault() as the first line in onSubmit
Forget it and the form triggers a full-page reload via GET/POST.
3. For checkboxes, use e.target.checked
4. e.currentTarget is the safe choice
e.target may be a child element (like a span) that received the actual click. The type of the element the handler is attached to comes from currentTarget.
5. e.stopPropagation() only works within the React tree
If an external library (e.g. jQuery) has attached a listener to document, React's stopPropagation won't stop it. In that case, use e.nativeEvent.stopImmediatePropagation().