Sub topic 3
Passing a function to `<form action>`
This chapter assumes you know React function components and useState, the difference between controlled and uncontrolled inputs, async functions with fetch, and the basics of the browser FormData API. The earlier chapters introduced Actions and useTransition. Here you apply them to forms.
What changes in React 19
In plain HTML, a form's action attribute is a URL. When the user submits, the browser sends a request to that URL and loads the response as a new page. React 19 lets you pass a function to the action prop instead:
<form action={search}>When the form is submitted, React does the following:
- It stops the browser's default navigation.
- It builds a
FormDataobject from the form's fields. - It calls your function with that object, inside a transition.
Because the call runs in a transition, your function is an Action. If it is async, React tracks it until the returned promise settles. That tracking is what the status hooks in later chapters read.
The function is an ordinary JavaScript function. It does not receive a submit event, and you do not call event.preventDefault() yourself.
The simplest form action
The next component sends a search query when the user submits.
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>
);
}There is no useState for the input, no onChange, and no onSubmit. The input is uncontrolled. The browser keeps its value, and React reads it from the form when the user submits. Pressing Enter in the input also submits, because the form has a submit button.
The encodeURIComponent call matters. The query comes from user input and goes into a URL, so it must be escaped.
How a submission flows
The diagram shows the order of events for an async Action.
While the promise is pending, React keeps the current UI interactive. The pending state is available to components through hooks, which later chapters cover.
Reading values from FormData
FormData is a standard browser API, and React does not wrap it. Four rules cover most problems.
- Only fields with a
nameare included. An<input>withoutnameis invisible toFormData. This is the most common bug when people first try form actions. - Values are strings or
Fileobjects. A number input gives you"42", not42. Convert it yourself. - Disabled fields are skipped. Browsers leave disabled controls out of form data. Use
readOnlyif the value must still be submitted. - Unchecked checkboxes are absent. A checked box contributes its
value(default"on"). An unchecked box contributes nothing, soformData.get("agree")returnsnull.
The following action shows these rules in use.
export function SubscribeForm() {
async function subscribe(formData) {
const email = String(formData.get("email") ?? "").trim();
const topics = formData.getAll("topic");
const wantsDigest = formData.get("digest") === "on";
const age = Number(formData.get("age"));
await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, topics, wantsDigest, age }),
});
}
return (
<form action={subscribe}>
<input name="email" type="email" required />
<input name="age" type="number" min="0" />
<label>
<input type="checkbox" name="topic" value="react" /> React
</label>
<label>
<input type="checkbox" name="topic" value="css" /> CSS
</label>
<label>
<input type="checkbox" name="digest" /> Weekly digest
</label>
<button type="submit">Subscribe</button>
</form>
);
}Points to notice:
formData.getreturnsFormDataEntryValue | null. TheString(... ?? "")pattern gives you a string even when the field is missing.getAll("topic")returns every checked box that shares the nametopic, as an array.- Browser validation attributes such as
requiredandtype="email"still run before the action is called. If the browser blocks the submit, your function is never invoked.
To collect everything at once, you can use Object.fromEntries(formData). It keeps only the last value for repeated names, so it is wrong for groups of checkboxes. Use getAll for those.
Action versus onSubmit
You can still use onSubmit. The two approaches differ in what they give you.
| Aspect | `onSubmit` handler | Function in `action` |
|---|---|---|
| Receives | The submit event | A `FormData` object |
| Default navigation | You must call `preventDefault()` | Prevented by React |
| Runs in a transition | No | Yes |
| Pending tracking | You write your own state | Built in, readable by hooks |
| Reads inputs from | State or `event.target` | The form's named fields |
If a form has both, onSubmit runs first. If it calls event.preventDefault(), the action is not run. Mixing them is rarely needed. Pick one per form.
Passing extra arguments with bind
An action receives only formData. To give it more data, such as the id of the record being edited, you have two options. One is a hidden input. The other is Function.prototype.bind, which pre-fills leading arguments.
async function renameItem(itemId, formData) {
const name = String(formData.get("name") ?? "").trim();
await fetch(`/api/items/${encodeURIComponent(itemId)}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
}
export function RenameItem({ itemId }) {
const renameThisItem = renameItem.bind(null, itemId);
return (
<form action={renameThisItem}>
<input name="name" />
<button type="submit">Rename</button>
</form>
);
}bind(null, itemId) returns a new function whose first argument is already itemId. React then calls it with formData, which arrives as the second argument. Do not use bind to carry secrets. Anything the client can see, the user can see.
Different buttons, different actions
A <button> or <input type="submit"> can have its own formAction prop. That function replaces the form's action when that button is the one that submits.
export function PostEditor() {
async function saveDraft(formData) {
await fetch("/api/posts/draft", { method: "POST", body: formData });
}
async function publish(formData) {
await fetch("/api/posts/publish", { method: "POST", body: formData });
}
return (
<form action={saveDraft}>
<textarea name="body" />
<button type="submit">Save draft</button>
<button type="submit" formAction={publish}>
Publish
</button>
</form>
);
}The first button uses the form's saveDraft. The second button runs publish. Passing formData directly as a fetch body sends it as multipart/form-data, and the browser sets the content type and boundary for you. Do not set a Content-Type header by hand in that case.
A button can also add data through its own name and value. Whichever button was used to submit appears in FormData under that name. This is a lighter alternative to separate functions when both paths share most logic.
Edge cases and gotchas
- Controlled inputs still work. You can keep
useStatefor live character counts or previews and also submit through an action. But reading fromFormDatamakes the state unnecessary for the submit path itself. - Errors escape the action. If your function throws or its promise rejects, the error is rethrown during rendering and goes to the nearest error boundary. For expected problems such as validation, return a value instead of throwing. The chapters on
useActionStateand error handling show how. - Nothing is returned to the form. The value your function returns is not shown anywhere on its own. To display a result, you need state.
useActionStateis built for that. - State updates after
awaitneed care. In React 19, state updates made after anawaitinside a plainstartTransitioncallback are not automatically part of the transition. Form actions carry the same constraint, so group follow-up updates deliberately and check results before relying on ordering. - Fast double submits. A user can submit again while the first request is running. Disable the button using the pending state, covered in the next chapters, or make the server idempotent.
- A string still works.
action="/search"keeps the classic browser behavior. React chooses the function path only when it receives a function. - File inputs. A file field gives a
FileinFormData. Remember to setencType="multipart/form-data"only when you want the browser fallback to work with a URL string. With a function action, you control the request, and passingformDataas thefetchbody handles files.
A short checklist
Before shipping a form that uses an action, check these points:
- Every field you want to read has a
name. - You convert strings to numbers, booleans, or dates explicitly.
- Missing fields are handled (
nullfromget, an empty array fromgetAll). - Expected failures are returned, not thrown.
- The server validates input on its own.
Exercise
A form uses <form action={save}>. Inside save(formData), formData.get("title") returns null even though the user typed a title into <input id="title" />. What is the likely cause, and what is the fix?
Show answer
The input has no name attribute. FormData includes only fields that have a name, so the id is ignored. Change the input to <input id="title" name="title" />.
Exercise
You need to send a record id to an action, along with the form fields, without adding a hidden input. Write the line that creates the action for <form action={...}>, assuming the function is updateItem(itemId, formData).
Show answer
const updateThisItem = updateItem.bind(null, itemId); and then <form action={updateThisItem}>. React calls it with formData as the second argument, after the bound itemId.
Exercise
A form has three checkboxes that all use name="topic". Why does Object.fromEntries(formData).topic give the wrong result, and what should you call instead?
Show answer
Object.fromEntries keeps only one value for a repeated name, so you lose the other checked boxes. Use formData.getAll("topic"), which returns an array of every checked value.