TypeScript
/Intermediate
React: Typing Events
Definition
Providing accurate types for Event Objects passed to event handler functions (like `onClick` or `onChange`) in React.
Explain Like I'm New
In vanilla JS, an event is just an `Event`. In React, events are wrapped in a 'SyntheticEvent'. If you have an `onChange` handler for an input, you must type the event so TypeScript knows it is allowed to read `event.target.value`.
Real World Example
An input handler: `const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { setValue(e.target.value); }`.
Common Use Cases
- •Form handling
- •Button clicks
- •Keyboard navigation
Interactive Example
import React, { useState } from 'react'; export function LoginForm() { const [text, setText] = useState(""); // 1. Typing a Form Input Change Event // Requires specifying WHICH HTML element triggered the change const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { setText(e.target.value); }; // 2. Typing a Form Submit Event const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); console.log("Submitted:", text); }; // 3. Typing a Mouse Event const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => { console.log("Clicked at X:", e.clientX); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={text} onChange={handleChange} /> <button onClick={handleClick} type="submit">Login</button> </form> ); }
Interview Questions
basic
- Do you need to type the event if the function is written completely inline?
intermediate
- What is the event type for an `<input>` onChange handler?
advanced
- What is the difference between `React.MouseEvent` and `MouseEvent`?