Sub topic 3
Passing a function to `<form action>`
This chapter assumes you know React function components, useState, async functions, and fetch. It also assumes you have seen the browser FormData API. You should already know what an Action is from the previous chapter: an async function that React runs inside a transition.
What changes in React 19
In plain HTML, a form's action attribute is a URL. React 19 also accepts a function. When the user submits the form, React does three things:
- It calls your function with the form's
FormDataobject. - It runs the call as an Action, inside a transition.
- It keeps the transition pending until the returned promise settles.
You don't call event.preventDefault(). React handles the submit event for you.
A first form action
export function SearchForm() {
async function search(formData) {
const query = formData.get("query");
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
console.log(await response.json());
}
return (
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
);
}The input has no value and no onChange, so it is uncontrolled. The browser keeps its text. When the form is submitted, React collects every named field into FormData and passes it to search.
Reading values from FormData
FormData reads fields by their name attribute, not by id or by component state. These methods cover most cases:
formData.get("email")returns the first value for that name. The type is a string, aFile, ornull.formData.getAll("topic")returns an array. Use it for checkboxes or a multi-select that share one name.Object.fromEntries(formData)turns the whole form into a plain object. If a name repeats, it keeps only the last value.
Because get can return null or a File, convert and check the value before you use it:
export function SignupForm() {
async function signup(formData) {
const email = String(formData.get("email") ?? "").trim();
const topics = formData.getAll("topic");
if (email === "") {
console.log("Email is required.");
return;
}
await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, topics }),
});
}
return (
<form action={signup}>
<input name="email" type="email" />
<label>
<input type="checkbox" name="topic" value="react" /> React
</label>
<label>
<input type="checkbox" name="topic" value="css" /> CSS
</label>
<button type="submit">Sign up</button>
</form>
);
}Logging an error is only a placeholder here. A later chapter shows how to return errors and render them.
How it differs from onSubmit
| Row | `onSubmit` handler | Function in `action` |
|---|---|---|
| Receives | The submit event | `FormData` |
| Default page navigation | You must call `preventDefault()` | React prevents it |
| Pending state | You track it yourself | Tracked by the transition |
| Input style | Often controlled with state | Often uncontrolled |
You can still use onSubmit for work that needs the event. For plain data entry, an action is usually shorter.
Common errors
- Missing
nameattribute. An input withoutnameis left out ofFormData, andgetreturnsnull. This is the most frequent cause of "my value is empty." - Expecting an event argument. The first argument is
FormData. Writing(event) => event.preventDefault()fails, becauseFormDatahas nopreventDefault. - Trusting the type.
getreturnsstring | File | null. Convert it withString(...)and check it before use. - Per-button actions. A
<button formAction={fn}>overrides the form'sactionfor that button. It is useful for "Save" and "Delete" buttons in one form, but it can surprise you when a different function runs than you expected.
Exercise
Exercise
A form uses <form action={save}> and contains <input id="title" />. Inside save(formData), formData.get("title") returns null. What is wrong, and what is the fix?
Show answer
The input has an id but no name. FormData collects fields by name, so the input is skipped. Add name="title" to the input.
Exercise
A group of checkboxes all use name="topic". Which FormData method returns every checked value, and what does it return?
Show answer
formData.getAll("topic"). It returns an array with the value of each checked box. get("topic") would return only the first one.