Sub topic 4
Responding to clicks and submits
This chapter shows how React connects user actions to code. You will wire up a click counter and the to-do form's submit handler, and you will learn the mistakes that most often break them. It assumes you have a Vite React project running, know useState from the previous chapters, and are comfortable with arrow functions and array spread.
How React handles events
An event is something the browser reports about the user, such as a click, a key press, or a form submission. In React you attach a handler (a function that runs when the event happens) by passing it as a prop on a JSX element. Three rules apply:
- Event prop names are camelCase:
onClick,onSubmit,onChange. In plain HTML they are lowercase. - The value is a function, not a string.
- React passes your handler an event object that wraps the browser's native event.
import { useState } from "react";
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return <button type="button" onClick={handleClick}>Clicked {count} times</button>;
}React listens for events at the root of your app and then calls the handler on the element that was clicked. The event object it gives you is a cross-browser wrapper around the native event. It has the usual members, such as target, preventDefault(), and stopPropagation(). You can reach the original event through event.nativeEvent, but you rarely need to.
Pass the function, do not call it
The most common first mistake is calling the handler inside JSX.
// Wrong: runs during render, and the result (undefined) becomes the handler
<button onClick={handleClick()}>Add</button>
// Right: React stores the function and calls it later
<button onClick={handleClick}>Add</button>With handleClick(), the function runs every time the component renders. If it also sets state, you get a loop of renders and React reports "Too many re-renders". You need the function itself, with no parentheses.
Handlers that need arguments
A handler often needs to know which item was clicked. React calls your handler with the event, so you cannot pass an extra argument directly. Wrap the call in an inline arrow function:
function TodoItem({ todo, onToggle, onDelete }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
<span>{todo.title}</span>
</label>
<button type="button" onClick={() => onDelete(todo.id)}>
Delete
</button>
</li>
);
}() => onDelete(todo.id) is itself a function. React stores it and calls it on click, and it then calls onDelete with the right id. Creating a new arrow function on each render costs almost nothing for a list this size, so you do not need useCallback here.
Naming conventions
Two naming habits make code easier to read:
- Name the prop
onSomething. It describes the event the child reports, such asonToggleoronDelete. - Name the function the parent defines
handleSomething, such ashandleToggle. It describes what the parent does in response.
The parent passes onToggle={handleToggle}. The child does not need to know what the parent does with it.
Submitting a form
A <form> is the right element for adding a to-do, even though a button with onClick would also work. Browsers submit a form when the user presses Enter in a text field or clicks a submit button. Listening to onSubmit covers both. A lone onClick on the button would miss the Enter key.
By default, the browser handles a submit by sending a request and reloading the page. That would wipe your React state. Calling event.preventDefault() cancels that default behavior.
import { useState } from "react";
export default function App() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState("");
function addTodo(event) {
event.preventDefault();
const title = text.trim();
if (!title) return;
setTodos([...todos, { id: crypto.randomUUID(), title, done: false }]);
setText("");
}
return (
<main>
<h1>To-do</h1>
<form onSubmit={addTodo}>
<label>
New task
<input value={text} onChange={(e) => setText(e.target.value)} />
</label>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
</main>
);
}Walk through the handler line by line:
event.preventDefault()stops the page reload. Forgetting it is the classic symptom of "my item appears for a split second and then vanishes".text.trim()removes surrounding whitespace, so a task of only spaces counts as empty.if (!title) return;ignores empty submissions without changing state.setTodos([...todos, ...])builds a new array. The next chapters cover why you must not usepush.setText("")clears the input after the item is added.
The value and onChange pair on the input makes it a controlled input. The next chapter covers that pattern in detail. For now, treat it as the way the handler reads what the user typed.
Button types matter
A <button> inside a form is a submit button by default. A button that does something else, such as Delete, must say type="button". Otherwise clicking it also submits the form. That is why the examples above set type on every button.
| Element | Default type | Effect inside a form |
|---|---|---|
| `<button>` | `submit` | Submits the form |
| `<button type="button">` | `button` | Only runs its `onClick` |
| `<button type="submit">` | `submit` | Submits the form (explicit) |
State updates inside handlers
Calling a setter does not change the variable right away. React schedules a re-render, and the new value appears in the next render. Inside the current handler, the old value is still in scope.
function handleClick() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
// count is still the old value here; after the render it is only 1 higher
}All three calls read the same count, so the counter grows by 1, not 3. React also batches the updates from one event into a single re-render, which keeps the UI efficient. When the new state depends on the previous state, pass an updater function:
function handleTripleClick() {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
}Here React queues the three updaters and applies them in order, so the counter grows by 3. For the to-do app, setTodos([...todos, newTodo]) is fine inside a single submit. Prefer the updater form setTodos((current) => [...current, newTodo]) when one handler may update the same state more than once, or when the update runs later, such as after a timer.
Event propagation
Most events bubble: after the handler on the target element runs, the same event triggers handlers on its parents. Suppose a whole <li> is clickable and the Delete button inside it also has a handler:
<li onClick={() => onSelect(todo.id)}>
{todo.title}
<button
type="button"
onClick={(event) => {
event.stopPropagation();
onDelete(todo.id);
}}
>
Delete
</button>
</li>Without stopPropagation(), clicking Delete would run onDelete and then onSelect, which bubbles up to the <li>. Use it sparingly. Stopping propagation can hide events from other code that expects them, so a better fix is often to avoid nesting two click targets.
Common errors
- Calling instead of passing.
onClick={handle()}runs during render. UseonClick={handle}oronClick={() => handle(id)}. - Missing
preventDefaulton submit. The page reloads and state resets. - Wrong casing.
onclickoronsubmitis ignored, and React warns about unknown properties. UseonClickandonSubmit. - Putting the handler on the button instead of the form. The Enter key then does nothing. Put
onSubmiton the<form>. - A non-submit button without
type="button". It submits the form by accident. - Reading state right after setting it. The variable holds the old value until the next render.
- Using a string.
onClick="handleClick()"is HTML syntax, and React does not support it.
Try it in the to-do app
Add the form from this chapter to App.jsx and run npm run dev. Then check each of these:
- Type a task and press Enter. The item should appear without a page reload.
- Type only spaces and submit. Nothing should be added.
- Remove
event.preventDefault()and submit again. Watch the page reload and the list disappear, then put the line back.
Exercise
A learner writes <button onClick={addTodo(text)}>Add</button> and sees the error "Too many re-renders" once addTodo calls setTodos. What is wrong, and how do you fix it?
Show answer
addTodo(text) is called while React renders the component, not when the user clicks. The call sets state, which triggers another render, which calls it again, forever. Pass a function instead: onClick={() => addTodo(text)}. Better, put the handler on the form with onSubmit={addTodo} and read text from state inside it.
Exercise
A to-do form has a text input, an Add button, and a Clear button that empties the input. Pressing Clear also adds a to-do. Why does this happen, and what is the one-attribute fix?
Show answer
Inside a form, a <button> without a type is a submit button, so clicking Clear fires the form's onSubmit as well as its onClick. Add type="button" to the Clear button so it runs only its onClick.