Typing Events & Refs in TypeScript
Use React.ChangeEvent, React.MouseEvent, and RefObject generics for DOM interactions.
React Synthetic Events
React wraps native DOM events in SyntheticEvent. Each event type has a specific generic: React.ChangeEvent<HTMLInputElement>, React.MouseEvent<HTMLButtonElement>, etc.
Typing onChange
The most common event is onChange on inputs. Type its handler with React.ChangeEvent<HTMLInputElement>.
function SearchInput() {
const [value, setValue] = useState('');
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
};
return <input value={value} onChange={handleChange} />;
}All lessons in this course
- Typing Props & Component Return Types
- Typing Events & Refs in TypeScript
- Generic Components & Utility Types
- Typing Context & Custom Hooks