function Search() {
const [query, setQuery] = useState("");
function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
setQuery(e.target.value);
}
function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
console.log(e.clientX);
}
return <><input value={query} onChange={handleChange} /><button onClick={handleClick}>Go</button></>;
}
Use React's event types, with the element type as the generic: React.ChangeEvent<HTMLInputElement> for an input's onChange, and React.MouseEvent<HTMLButtonElement> for a button's onClick.
React wraps DOM events in its own synthetic event types. Each one is generic over the element.
- With
React.ChangeEvent<HTMLInputElement>,e.target.valueis astring. - There are also
React.KeyboardEvent,React.FocusEventand others.
If you write the handler inline, as in onChange={(e) => setQuery(e.target.value)}, you need no annotation. TypeScript infers the type from the prop. Tip: when you are not sure of the type, write the handler inline first and hover over e in the editor.
You can also type the whole function with handler types, like React.ChangeEventHandler<HTMLInputElement>.
- Use
React.ChangeEvent<HTMLInputElement>for input changes. - Use
React.MouseEvent<HTMLButtonElement>for button clicks. - React event types are generic over the element type.
- Inline handlers get their event type inferred automatically.
- Handler types like
React.ChangeEventHandlertype the whole function.
Read more