Sub topic 12
Typing Event Handlers in TypeScript
This chapter shows how to give event handlers correct types in React with TypeScript. It assumes you know JavaScript functions and arrow functions, basic JSX, components and props, and useState. You also need basic TypeScript: type annotations and generics.
Why handlers need types
In plain JavaScript, a handler's e parameter can be anything. In TypeScript, a parameter with no type is an error under strict mode (it is an implicit any). You must tell the compiler what kind of event the handler receives. Then e.target.value and e.key are checked, and your editor can autocomplete them.
React ships these types in @types/react. Each one is generic: the type argument is the element the handler is attached to.
The basic pattern
Write the handler as a named function and annotate its event parameter with React.ChangeEvent<HTMLInputElement>.
import { useState } from 'react';
function NameInput() {
const [name, setName] = useState('');
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setName(e.target.value);
}
return <input value={name} onChange={handleChange} />;
}ChangeEvent<HTMLInputElement> tells TypeScript that e.target is an HTMLInputElement. So e.target.value is a string. Without the type argument, e.target would be a generic EventTarget with no value property, and the code would not compile.
Common event types
Most handlers use one of a small set of types.
| Event | Type | Typical element type |
|---|---|---|
| `onClick`, `onMouseEnter` | `React.MouseEvent<T>` | `HTMLButtonElement`, `HTMLDivElement` |
| `onChange` | `React.ChangeEvent<T>` | `HTMLInputElement`, `HTMLSelectElement`, `HTMLTextAreaElement` |
| `onKeyDown`, `onKeyUp` | `React.KeyboardEvent<T>` | `HTMLInputElement` |
| `onSubmit` | `React.FormEvent<T>` | `HTMLFormElement` |
| `onFocus`, `onBlur` | `React.FocusEvent<T>` | `HTMLInputElement` |
The pattern is the same each time: the event kind, then the element in angle brackets.
Typing a form submit handler
Here a form handler uses FormEvent<HTMLFormElement>, and the component's props are typed too.
import { useState } from 'react';
type SignupFormProps = {
onSubmit: (email: string) => void;
};
function SignupForm({ onSubmit }: SignupFormProps) {
const [email, setEmail] = useState('');
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
onSubmit(email);
}
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<button type="submit">Sign up</button>
</form>
);
}Look at the inline onChange arrow function. It has no annotation, yet e.target.value is typed. TypeScript infers the type of e from the onChange prop, because that prop is declared as ChangeEventHandler<HTMLInputElement>. This is called contextual typing. You only need to write the event type yourself when the handler is defined separately from the JSX.
Typing handler props
When a component receives a handler as a prop, type it as a function. Use a plain function type when the parent does not need the event. Use the event type when it does.
type ItemButtonProps = {
id: number;
onSelect: (id: number) => void;
onHover: (e: React.MouseEvent<HTMLButtonElement>) => void;
};
function ItemButton({ id, onSelect, onHover }: ItemButtonProps) {
return (
<button onClick={() => onSelect(id)} onMouseEnter={onHover}>
Item {id}
</button>
);
}React also exports handler types such as React.MouseEventHandler<HTMLButtonElement>. It is shorthand for (e: React.MouseEvent<HTMLButtonElement>) => void. Use whichever form your team finds easier to read.
Common errors
- Property 'value' does not exist on type 'EventTarget'. You wrote
React.ChangeEventwith no type argument, or usede.targeton aMouseEvent. Add the element type, such as<HTMLInputElement>. - Using the DOM
Eventtype. The globalEventandMouseEventtypes are for native listeners. React handlers receive synthetic events, so useReact.MouseEventand the other React types. - Wrong element type. Typing a
<select>handler asChangeEvent<HTMLInputElement>compiles in some cases but gives you the wrongtarget. Match the element in the JSX. - Reaching for
any. Annotatinge: anyremoves all checking. Let contextual typing work, or use the specific type.
Exercise
A <textarea> has onChange={handleChange}, where handleChange is declared as a separate function. Write the function signature so that e.target.value is typed as a string.
Show answer
function handleChange(e: React.ChangeEvent<HTMLTextAreaElement>) { ... }. The element type must match the JSX element, which is a textarea, so the type argument is HTMLTextAreaElement.
Exercise
Why does onChange={e => setEmail(e.target.value)} need no type annotation on e, but a separately declared function handleChange(e) does?
Show answer
In the inline version, TypeScript infers the type of e from the onChange prop's declared handler type (contextual typing). A separate function has no such context, so its parameter has no type until you annotate it. Under strict mode, that is an error.