Sub topic 12
Typing event handlers in TypeScript
This chapter assumes you can write function components with useState, you know how to attach handlers such as onClick and onChange, and you have read basic TypeScript annotations. Here you will learn which type to give the event parameter, when you can leave it out, and why TypeScript sometimes rejects a handler that looks correct.
Why handlers need types
A handler is an ordinary function that React calls with an event object. In plain JavaScript you never describe that object. In TypeScript, the editor needs to know what e.target.value is, whether e.key exists, and which element the event came from.
React's type definitions (the @types/react package) provide one event type per kind of event. Each type takes a type parameter, the element the handler is attached to:
React.ChangeEvent<HTMLInputElement>The type parameter describes e.currentTarget, the element that owns the handler. That choice affects the rest of this chapter.
When you do not need to write a type
When you write the handler inline, TypeScript infers the event type from the prop it is passed to:
function Search() {
return (
<input
onChange={e => console.log(e.target.value)}
/>
);
}onChange on an <input> expects a ChangeEventHandler<HTMLInputElement>, so e is already a ChangeEvent<HTMLInputElement>, and e.target.value is a string.
Inference stops once you move the handler into a named function. The function is checked on its own, before it is attached to anything, so its parameter has no context and becomes an implicit any. With strict enabled that is an error. You must write the type yourself:
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
console.log(e.target.value);
}Common event types
| Event type | Typical props | Notes |
|---|---|---|
| `React.MouseEvent<T>` | `onClick`, `onMouseEnter`, `onContextMenu` | Has `clientX`, `clientY`, `button`, and modifier keys. |
| `React.KeyboardEvent<T>` | `onKeyDown`, `onKeyUp` | Has `key`, `code`, and `shiftKey`. |
| `React.ChangeEvent<T>` | `onChange` | `T` is `HTMLInputElement`, `HTMLSelectElement`, or `HTMLTextAreaElement`. |
| `React.FormEvent<T>` | `onSubmit`, `onInput` | Use `HTMLFormElement` for submit handlers. |
| `React.FocusEvent<T>` | `onFocus`, `onBlur` | Has `relatedTarget`, the element gaining or losing focus. |
If you need the base type for a helper that accepts any event, use React.SyntheticEvent<T>. All the types above extend it.
Choosing the element type
The type parameter must match the element that carries the handler. A <select> produces ChangeEvent<HTMLSelectElement>, and a <textarea> produces ChangeEvent<HTMLTextAreaElement>. If you annotate a handler with the wrong element, TypeScript reports an error at the JSX prop, because the two element types are unrelated.
The following form uses three different event types:
import { useState } from 'react';
type Plan = 'free' | 'pro';
type SignupFormProps = {
onSubmit: (email: string, plan: Plan) => void;
};
function SignupForm({ onSubmit }: SignupFormProps) {
const [email, setEmail] = useState('');
const [plan, setPlan] = useState<Plan>('free');
function handleEmailChange(e: React.ChangeEvent<HTMLInputElement>) {
setEmail(e.target.value);
}
function handlePlanChange(e: React.ChangeEvent<HTMLSelectElement>) {
setPlan(e.target.value as Plan);
}
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
onSubmit(email, plan);
}
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={handleEmailChange} />
<select value={plan} onChange={handlePlanChange}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
<button type="submit">Sign up</button>
</form>
);
}The as Plan cast in handlePlanChange is needed because e.target.value is always typed as string. TypeScript cannot know that your <option> values match the Plan union. The cast is a promise you make, so keep the options and the type in sync.
target versus currentTarget
These two properties are typed differently, and the difference causes many errors.
e.currentTargetis the element the handler is attached to. Its type comes from your type parameter, so it is always precise.e.targetis the element that started the event. For most events it is typed as the genericEventTarget, because a click on a button can start on any child inside it.
ChangeEvent is the exception. React's types declare its target as EventTarget & T, which is why e.target.value works in the examples above. For mouse and keyboard events you should read from currentTarget:
function DeleteButton({ id }: { id: number }) {
function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
console.log(e.currentTarget.dataset.id);
}
return (
<button data-id={id} onClick={handleClick}>
Delete
</button>
);
}Writing e.target.dataset here fails to compile, because EventTarget has no dataset. If you really need the inner element, narrow it first with if (e.target instanceof HTMLElement).
Typing handler props
When a component accepts a handler as a prop, you have two options.
The first is a plain function type that describes only what the parent needs. It keeps the child independent of the DOM:
type ListProps = {
items: { id: number; name: string }[];
onSelect: (id: number) => void;
};The child calls onSelect(item.id) from its own inline arrow function. The parent never sees an event.
The second option is to forward the event, using one of React's handler types. Each event type has a matching ...Handler alias, such as MouseEventHandler<T>, ChangeEventHandler<T>, and FormEventHandler<T>:
type IconButtonProps = {
label: string;
onClick: React.MouseEventHandler<HTMLButtonElement>;
};
function IconButton({ label, onClick }: IconButtonProps) {
return (
<button type="button" onClick={onClick}>
{label}
</button>
);
}MouseEventHandler<HTMLButtonElement> means the same as (e: React.MouseEvent<HTMLButtonElement>) => void, but it is shorter and matches the names in React's own definitions.
If your component wraps a native element and should accept all of its props, you can borrow the types instead of listing them:
type ButtonProps = React.ComponentProps<'button'>;
type ClickHandler = ButtonProps['onClick'];ClickHandler is optional (it may be undefined), so check it before calling it.
Native listeners use different types
React's event types live in the React namespace. The browser has its own types with the same names, such as KeyboardEvent and MouseEvent, and these are what addEventListener uses. Inside useEffect, you work with the browser types:
import { useEffect } from 'react';
type ModalProps = {
onClose: () => void;
};
function Modal({ onClose }: ModalProps) {
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if (e.key === 'Escape') {
onClose();
}
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [onClose]);
return <div role="dialog">Press Escape to close</div>;
}Here KeyboardEvent is the global DOM type. Because it has the same name as React.KeyboardEvent, mixing them up is a common mistake. A handler annotated with React.KeyboardEvent cannot be passed to window.addEventListener, and a DOM KeyboardEvent cannot be passed to a JSX onKeyDown. When you call addEventListener with a literal event name like 'keydown', TypeScript infers the correct DOM type, so you can even drop the annotation if the handler is written inline.
Picking the right type
The decision path below covers most cases.
Common errors
- Implicit
anyon a named handler. Add the event type. Inference only works for inline handlers. - Wrong element in the type parameter. An
onChangeon a<select>needsHTMLSelectElement, notHTMLInputElement. Property 'value' does not exist on type 'EventTarget'. You reade.targeton a non-change event. Usee.currentTarget.- Handler works at runtime but fails to compile on
window. You used a React event type withaddEventListener. Switch to the DOM type. - Using
React.FormEventfor text input changes. It compiles in some setups but gives you a loosertarget. UseChangeEventforonChange.
Exercise
A teammate writes function handleKey(e: React.KeyboardEvent<HTMLInputElement>) { ... } and passes it to window.addEventListener('keydown', handleKey). TypeScript reports an error. Explain why, and show the corrected parameter type.
Show answer
addEventListener on window delivers the browser's own KeyboardEvent, not React's synthetic React.KeyboardEvent. The two types have the same name but are different, and the React one is also tied to an input element that does not exist for a window listener. Change the parameter to the global type: function handleKey(e: KeyboardEvent) { ... }. Use React.KeyboardEvent<HTMLInputElement> only for a JSX onKeyDown on an input.
Exercise
You extract an onClick handler for <button data-id="7"> into a named function and want to log 7. Which parameter type do you give it, and which property do you read the id from? Why not e.target?
Show answer
Use React.MouseEvent<HTMLButtonElement> and read e.currentTarget.dataset.id. currentTarget is typed as the button, the element carrying the handler. e.target is typed as the generic EventTarget, which has no dataset, and at runtime it can be a child element inside the button instead of the button itself.