Sub topic 6
Typing event handlers
This chapter assumes you can write React function components with useState, and that you know TypeScript unions and generics. It also assumes your project already uses the strict setting from the setup chapter. Without strict, many of the errors below will not appear.
Why event handlers need types
An inline handler such as <input onChange={(e) => ...} /> gets its type from the JSX attribute. TypeScript knows onChange on an <input> receives a change event for an HTMLInputElement, so e is typed for you.
That inference stops when you move the handler into its own function. A standalone function has no JSX attribute to read from, so under strict an untyped e is an implicit any error. You then have to write the event type yourself.
React wraps the browser's native event in a SyntheticEvent. React's type declarations model it with a family of generic types. Each one takes the element type as its type argument:
ChangeEvent<HTMLInputElement>The type argument controls what e.currentTarget is. That is the main thing you are choosing when you write one.
The common event types
| Event type | Typical attribute | Notes |
|---|---|---|
| `ChangeEvent<T>` | `onChange` | `T` is `HTMLInputElement`, `HTMLSelectElement`, or `HTMLTextAreaElement` |
| `FormEvent<T>` | `onSubmit`, `onInput` | `T` is usually `HTMLFormElement` |
| `MouseEvent<T>` | `onClick`, `onMouseEnter` | Has `clientX`, `button`, `shiftKey` |
| `KeyboardEvent<T>` | `onKeyDown`, `onKeyUp` | Has `key`, `code`, `ctrlKey` |
| `FocusEvent<T>` | `onFocus`, `onBlur` | Has `relatedTarget` |
| `ClipboardEvent<T>` | `onPaste`, `onCopy` | Has `clipboardData` |
| `DragEvent<T>` | `onDrop`, `onDragOver` | Has `dataTransfer` |
All of these are exported from react. Import them with import type or an inline type modifier.
Change events and forms
This example types a text input and a form submit:
import { useState, type ChangeEvent, type FormEvent } from "react";
export function NameForm({ onSubmit }: { onSubmit: (name: string) => void }) {
const [name, setName] = useState("");
function handleChange(e: ChangeEvent<HTMLInputElement>) {
setName(e.target.value);
}
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
onSubmit(name);
}
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={handleChange} />
<button type="submit">Save</button>
</form>
);
}useState("") infers string, so setName(e.target.value) type-checks because value is a string.
Each field type has its own element and its own value shape:
- A text input,
<textarea>, or<select>gives youe.target.valueas astring. - A checkbox gives you
e.target.checkedas aboolean. - A file input gives you
e.target.files, typedFileList | null. Check fornullbefore reading it. - A number input still gives
valueas astring. Convert it yourself withNumber(e.target.value).
A <select> needs HTMLSelectElement, not HTMLInputElement:
import { useState, type ChangeEvent } from "react";
type Role = "admin" | "viewer";
export function RolePicker() {
const [role, setRole] = useState<Role>("viewer");
function handleRole(e: ChangeEvent<HTMLSelectElement>) {
setRole(e.target.value as Role);
}
return (
<select value={role} onChange={handleRole}>
<option value="viewer">Viewer</option>
<option value="admin">Admin</option>
</select>
);
}The as Role is an assertion. The DOM always reports value as string, and TypeScript cannot know your <option> values match Role. If the options come from user data, validate the value at runtime instead of asserting.
If one handler serves several element types, use a union of element types:
ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>Only properties that exist on every member of the union are available. value and name qualify. checked does not.
target versus currentTarget
This distinction causes most event-typing confusion.
e.currentTargetis the element the handler is attached to. React types it with the type argument you supplied, for exampleHTMLButtonElement.e.targetis the element that started the event. It can be a descendant of the element you attached to, such as an<svg>inside a button.
For a general MouseEvent, e.target is typed as the plain EventTarget, which has no value or form. For ChangeEvent, React types target as EventTarget & T, which is why e.target.value works in the examples above.
Prefer currentTarget when you need element properties in a click or keyboard handler:
import type { KeyboardEvent, MouseEvent } from "react";
export function SearchBox({ onSearch }: { onSearch: (query: string) => void }) {
function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "Enter") {
onSearch(e.currentTarget.value);
}
}
function handleClear(e: MouseEvent<HTMLButtonElement>) {
e.currentTarget.form?.reset();
}
return (
<form>
<input onKeyDown={handleKeyDown} />
<button type="button" onClick={handleClear}>
Clear
</button>
</form>
);
}e.currentTarget.value is a string because the type argument is HTMLInputElement. e.currentTarget.form is HTMLFormElement | null, so the ?. is required.
Typing handler props
When a component accepts a handler from its parent, you have two choices. You can write the function signature yourself, or use one of React's handler aliases.
import type { MouseEventHandler } from "react";
interface IconButtonProps {
label: string;
onClick?: MouseEventHandler<HTMLButtonElement>;
}
export function IconButton({ label, onClick }: IconButtonProps) {
return (
<button aria-label={label} onClick={onClick}>
★
</button>
);
}MouseEventHandler<HTMLButtonElement> is shorthand for (event: MouseEvent<HTMLButtonElement>) => void. Each event type has a matching alias, such as ChangeEventHandler, FormEventHandler, and KeyboardEventHandler.
A parent can pass a function that takes the event, or one that takes no arguments. Both are valid, because TypeScript allows a function with fewer parameters:
<IconButton label="Star" onClick={() => console.log("starred")} />
<IconButton label="Star" onClick={(e) => console.log(e.clientX)} />In the second line, e is inferred as MouseEvent<HTMLButtonElement> without an annotation.
Pass values, not events, across component boundaries
The NameForm above declares onSubmit: (name: string) => void instead of exposing a FormEvent. This is usually the better design for your own components. A parent that receives a string does not need to know the child uses a form, and tests can call the prop with a plain value. Expose the raw event only when the parent genuinely needs it, as in a wrapper around a native element.
Common errors
- Implicit
anyone. You extracted a handler and left the parameter untyped. Add the event type from the table above. - "Property 'value' does not exist on type 'EventTarget'." You read
e.target.valuein aMouseEventorKeyboardEventhandler. Usee.currentTarget.valueand set the element type argument. - "Property 'value' does not exist on type 'HTMLElement'." You wrote
MouseEvent<HTMLElement>or left the type argument out. Name the specific element, such asHTMLInputElement. - Handler type mismatch on the attribute. You used
ChangeEvent<HTMLInputElement>on a<select>, or the global DOMMouseEvent. The type argument must match the element the attribute is on. - Wrong submit target.
FormEvent<HTMLButtonElement>on<form onSubmit>fails, because the handler is attached to the form. UseHTMLFormElement.
Choosing between inline and extracted handlers
| Situation | Choice |
|---|---|
| One short expression, such as `setOpen(true)` | Inline. The type is inferred. |
| Several lines, or reused on more than one element | Extract, and annotate the event. |
| Handler passed through props | Type the prop with an alias such as `MouseEventHandler<T>`. |
| Parent only needs a value | Pass a plain value in the callback, not the event. |
Exercise
A component renders <input onKeyDown={handleKey} />. Write the signature of handleKey so that it can read the input's current text with e.currentTarget.value. Then explain why e.target.value would not compile in a KeyboardEvent handler.
Show answer
function handleKey(e: KeyboardEvent<HTMLInputElement>), with KeyboardEvent imported from "react". The type argument makes e.currentTarget an HTMLInputElement, so value is a string. e.target is typed as the plain EventTarget for keyboard events, because the event may have started on any descendant element. EventTarget has no value property, so the compiler rejects e.target.value.
Exercise
A <select> handler is written as function onPick(e: ChangeEvent<HTMLInputElement>) and attached to <select onChange={onPick}>. What is wrong, and what is the fix?
Show answer
The type argument names the wrong element. A <select> produces events for HTMLSelectElement, so the handler type does not match the attribute and the compiler reports an error. Change the signature to ChangeEvent<HTMLSelectElement>. If the value must be a narrower union such as Role, assert it with as Role or validate it at runtime.