Events
React · Reference cheat sheet
Events
React · Reference cheat sheet
📋 Overview
React uses a SyntheticEvent system: camelCase props (onClick, onChange) and functions as handlers. Behavior is consistent across browsers.
🔧 Core concepts
- Naming —
onClick,onSubmit,onKeyDown(notonclick). - Handler — pass a function:
onClick=\{handleClick\}, notonClick=\{handleClick()\}. - Event object —
event.preventDefault(),event.stopPropagation(),event.target. - Passing data — wrap:
onClick=\{() => onSelect(id)\}oronClick=\{onSelect.bind(null, id)\}.
💡 Examples
export function SearchForm({ onSearch }: { onSearch: (q: string) => void }) {
function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
const data = new FormData(e.currentTarget);
onSearch(String(data.get("q") ?? ""));
}
return (
<form onSubmit={handleSubmit}>
<input name="q" type="search" />
<button type="submit">Search</button>
</form>
);
}function List({ items, onSelect }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>
<button type="button" onClick={() => onSelect(item.id)}>
{item.label}
</button>
</li>
))}
</ul>
);
}⚠️ Pitfalls
- Calling the handler immediately (
onClick=\{fn()\}) runs it during render. - Don’t rely on the event after an
await— React pools/reuses in older versions; read values first or useevent.persist()only if needed on old React. - Prefer
onChangeon inputs for controlled components, not onlyonBlur.
🔗 Related
- props.md — callback props
- jsx.md — JSX attributes
- useState.md — controlled inputs
- component.md — handlers in components