Handling Events
Respond to clicks, input and more with camelCase event props.
Syntax
<button onClick={handleClick}>Save</button>React events are attached with camelCase props like onClick, onChange and onSubmit. You pass a function — not a string and not the result of calling it.
Passing the handler correctly
- Correct:
onClick={handleClick}(pass the function). - Also fine:
onClick={() => doThing(id)}(an inline arrow). - Wrong:
onClick={handleClick()}— this calls it immediately during render.
Handlers receive a synthetic event. Call e.preventDefault() to stop default browser behavior, such as a form reloading the page.
Example
function Form() {
function handleSubmit(e) {
e.preventDefault();
console.log('submitted');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Send</button>
</form>
);
}When to use it
- A drag-and-drop kanban board attaches onDragStart and onDrop event handlers to task cards so users can move items between columns without page navigation.
- A search bar uses onChange on an input to call a debounced search function every time the user types, keeping results fresh without querying on every keystroke.
- A keyboard-shortcut system attaches onKeyDown to a container so users can trigger save, undo, or navigate without reaching for the mouse.
More examples
Button click handler
Attaches a named handler function to onClick — the recommended style for handlers with more than one line.
function AlertButton() {
function handleClick() {
console.log('Button clicked!');
}
return <button onClick={handleClick}>Click me</button>;
}Input onChange event
Reads e.target.value inside an inline onChange handler to keep input state in sync with what the user types.
import { useState } from 'react';
function SearchBox() {
const [query, setQuery] = useState('');
return (
<input
type="search"
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Search..."
/>
);
}Passing data to an event handler
Wraps the handler in an arrow function so the item's ID is captured in the closure and passed up to the parent.
function ProductList({ products, onAddToCart }) {
return (
<ul>
{products.map(p => (
<li key={p.id}>
{p.name}
<button onClick={() => onAddToCart(p.id)}>
Add to cart
</button>
</li>
))}
</ul>
);
}
Discussion