Sub topic 4
Responding to clicks and submits
This chapter assumes you can write function components, pass props, and read state with useState. It also assumes you know basic HTML forms. Here you will connect user actions to your code with event handlers.
How React handles events
An event is something the user does, such as a click or a form submission. In JSX you attach a handler by passing a function to a prop named in camelCase: onClick, onSubmit, onChange.
React calls your handler with an event object. This object wraps the browser's native event. It has the same useful members, such as preventDefault(), target, and currentTarget.
Pass the function, do not call it
The most common mistake is calling the handler while writing the JSX.
<button onClick={handleClick()}>Wrong</button> {/* runs during render */}
<button onClick={handleClick}>Right</button> {/* runs on click */}The first version runs handleClick every time the component renders. It then passes the return value, usually undefined, to onClick. If that function sets state, you get an infinite render loop.
Passing arguments
A handler receives only the event. To tell it which item was clicked, wrap the call in an arrow function:
<button type="button" onClick={() => onDelete(todo.id)}>Delete</button>The arrow function is created during render, but onDelete(todo.id) runs only when the click happens.
Handling a form submit
A form's default behavior is to send a request and reload the page. A single-page app must stop that with event.preventDefault(). The example below reads the input with the browser's FormData. The next chapter replaces this with a controlled input.
import { useState } from "react";
export default function App() {
const [todos, setTodos] = useState([]);
function handleSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const title = String(new FormData(form).get("title")).trim();
if (!title) return;
setTodos([...todos, { id: crypto.randomUUID(), title }]);
form.reset();
}
function handleDelete(id) {
setTodos(todos.filter((todo) => todo.id !== id));
}
return (
<main>
<h1>To-do</h1>
<form onSubmit={handleSubmit}>
<label>
New task
<input name="title" />
</label>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
{todo.title}
<button type="button" onClick={() => handleDelete(todo.id)}>
Delete
</button>
</li>
))}
</ul>
</main>
);
}Both handlers call setTodos with a new array. React then re-renders the component. Later chapters explain why the arrays are built with the spread syntax and filter.
Common errors
- Listening to the button, not the form. Put
onSubmiton the<form>. Then pressing Enter in the input also submits, which a buttononClickwould miss. - Forgetting
type="button". A<button>inside a form submits it by default. Give non-submit buttonstype="button". - Using
event.targetwhen you needcurrentTarget.targetis the element that was clicked, which may be a child.currentTargetis the element the handler is attached to. Here that is the form. - Writing
onclickoronSubmit="...". Props are camelCase and take functions, not strings.
Exercise
A to-do app has <button onClick={deleteTodo(todo.id)}>Delete</button>. Items disappear as soon as the list renders, and the console may report too many re-renders. What is wrong, and how do you fix it?
Show answer
deleteTodo(todo.id) is called during render, and its result is passed to onClick. Wrap it in an arrow function so it runs only on click: onClick={() => deleteTodo(todo.id)}.