Sub topic 12
Responding to events
This chapter assumes you can write a function component, pass props, and use curly braces and camelCase attributes in JSX. It also assumes you know JavaScript arrow functions.
Handlers are props on elements
An event handler is a function that React calls when something happens in the browser, such as a click or a key press. You attach one with a camelCase attribute like onClick, onChange, or onSubmit. The attribute takes a function inside curly braces.
function SaveButton() {
function handleClick() {
alert('Saved!');
}
return <button onClick={handleClick}>Save</button>;
}Define handlers inside the component, usually with a name that starts with handle. Inline arrow functions also work and suit one-line handlers:
<button onClick={() => alert('Saved!')}>Save</button>Pass the function, don't call it
The most common mistake is calling the function instead of passing it.
// Wrong: runs during render, and its return value becomes the handler
<button onClick={handleClick()}>Save</button>
// Right: React calls handleClick later, when the click happens
<button onClick={handleClick}>Save</button>With handleClick(), the alert fires every time the component renders, and onClick receives undefined. If a handler needs arguments, wrap the call in an arrow function:
<button onClick={() => handleDelete(item.id)}>Delete</button>The event object
React passes your handler an event object. It describes what happened, and it wraps the browser's native event so it behaves the same across browsers. Two members matter most:
event.targetis the element that triggered the event. For an input,event.target.valueholds the current text.event.preventDefault()stops the browser's default action, such as a form submit reloading the page.
function SignupForm() {
function handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
console.log('Email:', data.get('email'));
}
return (
<form onSubmit={handleSubmit}>
<input name="email" type="email" />
<button type="submit">Join</button>
</form>
);
}Events also bubble up through parent elements. Call event.stopPropagation() if a parent's handler should not run.
Handlers passed as props
A child component often triggers an action that the parent owns. The parent passes a function as a prop, and the child calls it. By convention, the prop name starts with on, and the parent's function starts with handle.
import { useState } from 'react';
function IconButton({ label, onPress }) {
return <button onClick={onPress}>{label}</button>;
}
export default function App() {
const [count, setCount] = useState(0);
function handleAdd() {
setCount(count + 1);
}
return (
<>
<IconButton label="Add" onPress={handleAdd} />
<p>Count: {count}</p>
</>
);
}useState is covered in the next chapter. Here, read setCount as "store a new value and re-render". The point is the data flow: data goes down through props, and events go up through function props.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Handler runs on page load | Wrote `onClick={fn()}` | Use `onClick={fn}` |
| Page reloads on form submit | Missing `preventDefault` | Call `event.preventDefault()` |
| Handler never fires on a custom component | `onClick` is not forwarded to a DOM element | Pass it down and attach it to a real element |
| Warning about `onclick` | Lowercase attribute name | Use camelCase `onClick` |
Note that a custom component such as <IconButton onClick={...} /> does not get click behavior automatically. The prop is just data until the component attaches it to a DOM element.
Exercise
A teammate writes <button onClick={deleteItem(item.id)}>Delete</button> and the item is deleted as soon as the list renders. Why does this happen, and what is the fix?
Show answer
deleteItem(item.id) is called during rendering, and its return value is given to onClick. Pass a function instead: onClick={() => deleteItem(item.id)}.