How do you type an event handler function, such as a button's onClick handler, in TypeScript?
Short answer
React provides specific event types, like React.MouseEvent, that describe exactly what information a given event handler receives, letting TypeScript check that you are using the event object correctly, such as accessing properties that actually exist on that specific kind of…
Advertisement
AModel answer
React provides specific event types, like React.MouseEvent, that describe exactly what information a given event handler receives, letting TypeScript check that you are using the event object correctly, such as accessing properties that actually exist on that specific kind of event.
function Button() {
function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
console.log('Button clicked at', event.clientX, event.clientY);
}
return <button onClick={handleClick}>Click Me</button>;
}Real-world example
A form's submit handler is correctly typed as React.FormEvent, letting TypeScript immediately flag a mistake if the developer tries to access a property that does not actually exist on a form submission event.
Likely follow-ups
- How does the correct event type differ between a button click, a form submission, and typing into an input?
- What happens if you use the wrong event type for a specific handler?
Related topics