Handling Events
The reading list needs to react to people: a Remove button, a Mark as read checkbox, a search box. React attaches behaviour straight onto the JSX, with one rule that catches nearly every beginner at least once.
The rule
Hand React a function; never call it yourself.
Events use camelCase props — onClick, onChange, onSubmit, onKeyDown — and each takes a function. React calls it later, when the event happens:
function LikeButton() {
function handleClick() {
alert('Thanks for the like!');
}
return <button onClick={handleClick}>Like</button>;
}Note onClick={handleClick} — no parentheses. With parentheses, handleClick() would run immediately, during render, and onClick would receive its return value.
Passing an argument? Wrap the call in an arrow function, which is itself a function React can call later:
<button onClick={() => removeBook(book.id)}>Remove</button>The event object. React passes your handler an event object as its first argument. Two methods matter most:
e.preventDefault()stops the browser's built-in behaviour, such as a form reloading the page on submit.e.stopPropagation()stops the event bubbling up to handlers on parent elements.
function SearchForm({ onSearch }) {
function handleSubmit(e) {
e.preventDefault();
onSearch(e.target.elements.q.value);
}
return (
<form onSubmit={handleSubmit}>
<input name="q" />
<button>Search</button>
</form>
);
}Naming convention. Handlers inside a component are called handleSomething. Props that accept handlers from a parent are called onSomething, like onSearch above. That lets a parent decide what a click means while the child decides where the click happens.
Bubbling. An event starts at the element that was clicked and travels up through its ancestors. If a whole BookCard opens details on click and the Remove button inside it also has a handler, one click triggers both — unless the button calls e.stopPropagation().
Events are also where side effects belong — a handler runs once per click, not once per render, so it is free to change things.