Events
React events look like DOM events but are synthetic: pooled wrappers around the native event with a consistent API across browsers. Handler names are camelCase; you pass a function, not a string.
Click, change, key, submit
EXAMPLE
// Basic
<button onClick={() => console.log('clicked')}>Tap</button>
// Read the event
<input onChange={e => setQuery(e.target.value)} value={query} />
// Forms — prefer onSubmit + preventDefault
function LoginForm() {
const [email, setEmail] = useState('');
function submit(e) {
e.preventDefault();
api.signIn(email);
}
return (
<form onSubmit={submit}>
<input value={email} onChange={e => setEmail(e.target.value)} />
<button type="submit">Sign in</button>
</form>
);
}
// Keyboard
<input onKeyDown={e => {
if (e.key === 'Enter') save();
if (e.key === 'Escape') cancel();
}} />
// Pass extra args via a closure (don't string-build)
<button onClick={() => remove(item.id)}>Delete</button>
Why it matters
Inline arrow handlers are fine. The “creates a new function each render” concern is almost always premature optimisation — only matters if you’re passing it to a memoised, deeply-mounted subtree.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
function Form() {
const onSubmit = (e) => { e.preventDefault(); console.log('sent'); };
return <form onSubmit={onSubmit}><button>Send</button></form>;
}
Try it Yourself »
Discussion
Loading…