Careeroza
Typing Events
Event Handler Types
React event objects are typed by event kind and element: ChangeEvent<HTMLInputElement>, FormEvent<HTMLFormElement>, MouseEvent<HTMLButtonElement>. Inline handlers get them automatically; separate functions need the annotation.
"use client";
import { useState, type ChangeEvent, type FormEvent, type KeyboardEvent } from "react";
export function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState("");
function handleChange(e: ChangeEvent<HTMLInputElement>) {
setQuery(e.target.value);
}
function handleSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
onSearch(query.trim());
}
function handleKey(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "Escape") setQuery("");
}
return (
<form onSubmit={handleSubmit}>
<input value={query} onChange={handleChange} onKeyDown={handleKey} placeholder="Search products" />
<select onChange={(e) => console.log(e.target.value)}> {/* e inferred: ChangeEvent<HTMLSelectElement> */}
<option value="relevance">Relevance</option>
<option value="price">Price</option>
</select>
</form>
);
}Tip: Not sure of an event type? Write the handler inline, hover over e in VS Code, and copy the type.