Typing Synthetic Events and Form Elements
Typing Synthetic Events and Form Elements
React normalizes browser events into cross-browser SyntheticEvent wrappers. In TypeScript, passing inline event handlers often benefits from automatic type inference, but extracting handlers into separate named functions requires explicit typing of both the event wrapper and the underlying HTML element.
1. Common React Event Types
React exports dedicated types for every event category in the React namespace:
| Event Handler | React Event Type | Target Element Generic |
|---|---|---|
onChange (text/select) | React.ChangeEvent<T> | HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement |
onClick | React.MouseEvent<T> | HTMLButtonElement, HTMLDivElement |
onSubmit | React.FormEvent<T> | HTMLFormElement |
onKeyDown / onKeyUp | React.KeyboardEvent<T> | HTMLInputElement, HTMLElement |
onFocus / onBlur | React.FocusEvent<T> | HTMLInputElement |
onDrag / onDrop | React.DragEvent<T> | HTMLDivElement |
2. Typing Form Input Changes
When managing form state, pass the exact HTML form element generic to React.ChangeEvent:
3. Keyboard Event Handling & Key Filtering
4. e.target vs e.currentTarget
TypeScript differentiates between e.target and e.currentTarget:
e.currentTarget: The element to which the event handler is currently attached (strictly typed to genericT).e.target: The element that dispatched the original event (could be a nested child span or icon, typed asEventTarget).
Always use e.currentTarget when reading properties on the registered element container!
Practice Quiz
Polymorphic Component Typing with As and ComponentPropsWithoutRef
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Typing React Hooks, Generics, and Refs | Polymorphic Component Typing with As and ComponentPropsWithoutRef |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.