Sub topic 6
Typing event handlers
This chapter assumes you can write React function components with props and state, and that you know TypeScript interfaces, unions, and generics. It also assumes the tsconfig.json from the setup chapter, with strict turned on. Here you will learn how React's event types work and how to pick the right one.
Why event types matter
React wraps native browser events in its own synthetic event objects. Each one has a type from @types/react, and most take the element as a type parameter:
ChangeEvent<HTMLInputElement>FormEvent<HTMLFormElement>MouseEvent<HTMLButtonElement>KeyboardEvent<HTMLInputElement>
The type parameter sets the type of e.currentTarget, the element the handler is attached to. With the right parameter, e.target.value and e.currentTarget.value are typed as string instead of failing to compile.
A typed form
This component uses two handlers. Each one names its event type and the element it is attached to.
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. The onSubmit prop is a function type. Its parameter list tells callers what the component will pass.
Inline handlers need no annotation
When you write the function directly in the JSX attribute, TypeScript infers the event type from the prop. You do not annotate it.
export function Save() {
return (
<button onClick={(e) => console.log(e.currentTarget.textContent)}>
Save
</button>
);
}Here e is a MouseEvent<HTMLButtonElement>. Annotations are needed only when you pull the handler out into its own function. A separate function has no context, so its parameter would otherwise be an implicit any, which strict rejects.
Handler types as props
A component often accepts a handler from its parent. Use the handler types that React exports. They describe the whole function, so you do not write the parameter type by hand.
import type { ChangeEventHandler, MouseEventHandler } from "react";
interface ToolbarProps {
onSearch: ChangeEventHandler<HTMLInputElement>;
onReset: MouseEventHandler<HTMLButtonElement>;
}
export function Toolbar({ onSearch, onReset }: ToolbarProps) {
return (
<div>
<input onChange={onSearch} />
<button onClick={onReset}>Reset</button>
</div>
);
}ChangeEventHandler<T> is shorthand for (event: ChangeEvent<T>) => void. If the parent only needs a value, a narrower prop such as onSearch: (value: string) => void is often a better contract. It hides React's event objects from the parent.
Choosing the right type
| Situation | Type |
|---|---|
| Text input, select, textarea value changes | `ChangeEvent<HTMLInputElement>` (or `HTMLSelectElement`, `HTMLTextAreaElement`) |
| Form submission | `FormEvent<HTMLFormElement>` |
| Click on a button | `MouseEvent<HTMLButtonElement>` |
| Key press in an input | `KeyboardEvent<HTMLInputElement>` |
| Focus or blur | `FocusEvent<HTMLInputElement>` |
If you are unsure, hover over the attribute in your editor, such as onChange, to see the expected handler type.
How the pieces connect
Common errors
- Annotating with
Eventinstead of a React event type.Eventis the DOM type and does not match React's handler props. - Using
ChangeEvent<HTMLInputElement>on a<select>. UseHTMLSelectElement. - Forgetting
e.preventDefault()in a submit handler. The compiler will not catch this, and the page will reload.
Exercise
You move an inline onKeyDown={(e) => ...} handler on an <input> into a named function handleKey. What parameter type should you give it, and why is the annotation now required?
Show answer
Use KeyboardEvent<HTMLInputElement>, imported from react. As an inline arrow function, TypeScript infers the event type from the onKeyDown prop. A separate function has no such context, so under strict its parameter would be an implicit any and cause an error.
Exercise
A parent passes onChange={handleChange} to a <select>, and handleChange is typed (e: ChangeEvent<HTMLInputElement>) => void. Why does TypeScript report an error, and how do you fix it?
Show answer
The <select> expects a handler for ChangeEvent<HTMLSelectElement>, and the handler's parameter is for an input element. Change the parameter type to ChangeEvent<HTMLSelectElement>.