| TypeScript Props for React Components :👈 | 👉:How to Type Custom React Hooks |
How to Type React Event Handlers |
How to Type React Event Handlers in TypeScript
1. Introduction
In React, event handlers are functions that execute when users interact with elements such as buttons, input fields, forms, and dropdowns.
When using TypeScript with React, we should define the correct event types to ensure type safety and better IntelliSense support.
Common React events include:
- Click events
- Input change events
- Form submission events
- Keyboard events
- Mouse events
- Focus and blur events
2. Understanding React Event Types
React provides predefined event types through the React package.
Some commonly used event types are:
| Event Type | Purpose |
|---|---|
MouseEvent |
Mouse interactions such as clicking. |
ChangeEvent |
Input and select value changes. |
FormEvent |
Form-related events. |
KeyboardEvent |
Keyboard interactions. |
FocusEvent |
Focus and blur events. |
ClipboardEvent |
Copy, cut, and paste events. |
DragEvent |
Drag-and-drop interactions. |
PointerEvent |
Mouse, touch, and pen pointer interactions. |
These are React event types, not the native browser event types.
3. Typing Button Click Events
Use React.MouseEvent<HTMLButtonElement> to type a button click event.
Example
import type { MouseEvent } from "react";
function App() {
const handleClick = (
event: MouseEvent<HTMLButtonElement>
) => {
console.log("Button clicked");
console.log(event.currentTarget);
};
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default App;
Explanation:
MouseEventrepresents a React mouse event.HTMLButtonElementspecifies that the event belongs to a button.event.currentTargetrefers to the element where the handler is attached.onClickreceives the event handler.
4. Typing Input Change Events
Use ChangeEvent<HTMLInputElement> for input field changes.
Example
import { useState } from "react";
import type { ChangeEvent } from "react";
function App() {
const [name, setName] = useState("");
const handleChange = (
event: ChangeEvent<HTMLInputElement>
) => {
setName(event.target.value);
};
return (
<div>
<input
type="text"
value={name}
onChange={handleChange}
/>
<p>Name: {name}</p>
</div>
);
}
export default App;
Explanation:
ChangeEvent<HTMLInputElement>defines the input change event.event.target.valuegets the current input value.setName()updates the React state.
5. Typing Textarea Change Events
For a textarea, use ChangeEvent<HTMLTextAreaElement>.
Example
import type { ChangeEvent } from "react";
function App() {
const handleChange = (
event: ChangeEvent<HTMLTextAreaElement>
) => {
console.log(event.target.value);
};
return (
<textarea
onChange={handleChange}
placeholder="Enter your message"
/>
);
}
6. Typing Select Dropdown Events
Use ChangeEvent<HTMLSelectElement> for dropdown selection changes.
Example
import type { ChangeEvent } from "react";
function App() {
const handleChange = (
event: ChangeEvent<HTMLSelectElement>
) => {
console.log(event.target.value);
};
return (
<select onChange={handleChange}>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
</select>
);
}
7. Typing Form Submit Events
Use FormEvent<HTMLFormElement> for form submission.
Example
import type { FormEvent } from "react";
function App() {
const handleSubmit = (
event: FormEvent<HTMLFormElement>
) => {
event.preventDefault();
console.log("Form submitted");
};
return (
<form onSubmit={handleSubmit}>
<input type="text" required />
<button type="submit">
Submit
</button>
</form>
);
}
Important: Use event.preventDefault() to prevent the browser's default form submission behavior when handling the submission in React.
8. Typing Keyboard Events
Use KeyboardEvent<HTMLInputElement> to handle keyboard interactions on an input.
Example
import type { KeyboardEvent } from "react";
function App() {
const handleKeyDown = (
event: KeyboardEvent<HTMLInputElement>
) => {
if (event.key === "Enter") {
console.log("Enter key pressed");
}
};
return (
<input
type="text"
onKeyDown={handleKeyDown}
placeholder="Press Enter"
/>
);
}
Common keyboard event properties:
event.key– identifies the pressed key.event.ctrlKey– checks whether Ctrl is pressed.event.shiftKey– checks whether Shift is pressed.event.altKey– checks whether Alt is pressed.
9. Typing Focus and Blur Events
Use FocusEvent for focus and blur interactions.
Example
import type { FocusEvent } from "react";
function App() {
const handleFocus = (
event: FocusEvent<HTMLInputElement>
) => {
console.log("Input focused");
};
const handleBlur = (
event: FocusEvent<HTMLInputElement>
) => {
console.log("Input lost focus");
};
return (
<input
type="text"
onFocus={handleFocus}
onBlur={handleBlur}
/>
);
}
10. Inline Event Handler Typing
TypeScript can often infer the event type automatically when the handler is written directly inside JSX.
Example
function App() {
return (
<input
type="text"
onChange={(event) => {
console.log(event.target.value);
}}
/>
);
}
Here, TypeScript automatically understands that event is a React change event for an HTML input element.
Recommendation: Inline inference is convenient for small handlers. Explicit event types are useful when extracting handlers into separate functions or passing them as props.
11. Typing Event Handler Props
Sometimes a parent component passes an event handler to a child component through props.
Example: Button Component
import type { MouseEventHandler } from "react";
interface ButtonProps {
onClick: MouseEventHandler<HTMLButtonElement>;
label: string;
}
function CustomButton({
onClick,
label
}: ButtonProps) {
return (
<button onClick={onClick}>
{label}
</button>
);
}
function App() {
const handleClick = () => {
console.log("Button clicked");
};
return (
<CustomButton
label="Save"
onClick={handleClick}
/>
);
}
MouseEventHandler<HTMLButtonElement> is a predefined React type for a button mouse event handler.
Other Useful Event Handler Types
| Type | Purpose |
|---|---|
MouseEventHandler<T> |
Mouse event handlers |
ChangeEventHandler<T> |
Change event handlers |
FormEventHandler<T> |
Form event handlers |
KeyboardEventHandler<T> |
Keyboard event handlers |
FocusEventHandler<T> |
Focus event handlers |
12. Difference Between target and currentTarget
This is an important concept when working with React events.
event.targetrefers to the element that originally triggered the event.event.currentTargetrefers to the element on which the event handler is registered.
Example
import type { MouseEvent } from "react";
function App() {
const handleClick = (
event: MouseEvent<HTMLDivElement>
) => {
console.log("Target:", event.target);
console.log("Current Target:", event.currentTarget);
};
return (
<div onClick={handleClick}>
Parent Div
<button>
Child Button
</button>
</div>
);
}
When the child button is clicked:
event.targetrefers to the button.event.currentTargetrefers to the parent div.
This behavior is useful when implementing event bubbling and event delegation.
13. Event Types Reference
| HTML Element | React Event Type | Common Event |
|---|---|---|
| Button | MouseEvent<HTMLButtonElement> |
onClick |
| Input | ChangeEvent<HTMLInputElement> |
onChange |
| Textarea | ChangeEvent<HTMLTextAreaElement> |
onChange |
| Select | ChangeEvent<HTMLSelectElement> |
onChange |
| Form | FormEvent<HTMLFormElement> |
onSubmit |
| Input | KeyboardEvent<HTMLInputElement> |
onKeyDown |
| Input | FocusEvent<HTMLInputElement> |
onFocus / onBlur |
14. Common Mistakes
- Using the wrong HTML element type: Use
HTMLInputElementfor inputs andHTMLButtonElementfor buttons. - Using native DOM event types incorrectly: React handlers normally use React event types such as
ChangeEventandMouseEvent. - Using any for event parameters: Avoid
anybecause it removes type safety. - Confusing target and currentTarget: They can refer to different elements when events bubble.
- Calling a handler instead of passing it: Use
onClick={handleClick}, notonClick={handleClick()}, unless immediate execution is specifically intended. - Forgetting preventDefault: Prevent the browser's default form submission when your React handler needs to manage it.
15. Best Practices
- Use React's predefined event types.
- Specify the correct HTML element type using generics.
- Allow TypeScript to infer event types for simple inline handlers.
- Use explicit types for reusable event handler functions.
- Use handler types such as
MouseEventHandlerwhen defining event handler props. - Avoid using
anyfor event parameters. - Understand the difference between
targetandcurrentTarget.
16. Interview Questions and Answers
Q1. How do you type a button click event in React TypeScript?
Use MouseEvent<HTMLButtonElement>.
Q2. How do you type an input change event?
Use ChangeEvent<HTMLInputElement>.
Q3. What is the difference between MouseEvent and MouseEventHandler?
MouseEvent represents the event object received by a handler. MouseEventHandler represents the function type used to handle that event.
Q4. How do you type a form submission event?
Use FormEvent<HTMLFormElement>.
Q5. Can TypeScript automatically infer event types?
Yes. TypeScript can infer event types when handlers are assigned directly to JSX event properties.
Q6. What is the difference between target and currentTarget?
target identifies the original event source, whereas currentTarget identifies the element where the handler is registered.
Q7. How do you type an event handler passed through props?
Use a predefined handler type such as MouseEventHandler<HTMLButtonElement> or define a function signature explicitly.
Q8. Which event type is used for keyboard events?
Use KeyboardEvent<HTMLInputElement> for keyboard events on an input element.
17. Key Takeaways
- React provides predefined event types for TypeScript.
- Use
MouseEventfor mouse interactions. - Use
ChangeEventfor input and select changes. - Use
FormEventfor form events. - Use
KeyboardEventfor keyboard interactions. - Use the correct HTML element type inside the event generic.
- TypeScript can infer event types in inline JSX handlers.
- Use handler types when passing callbacks through component props.
Remember: React event types provide type safety for event handlers. The most important part is selecting the correct event type and the correct HTML element type.
| TypeScript Props for React Components :👈 | 👉:How to Type Custom React Hooks |
Comments and Discussion