You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 7ad9c1d
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: src/content/reference/react-dom/components/form.md
+91-23Lines changed: 91 additions & 23 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -48,7 +48,7 @@ To create interactive controls for submitting information, render the [built-in
48
48
#### Caveats {/*caveats*/}
49
49
50
50
* If you pass a function to `action` or `formAction`, the HTTP method will be `POST` regardless of the value of the `method` prop.
51
-
* If you pass a function to `action` or `formAction`, React resets all [uncontrolled](/reference/react-dom/components/input#reading-the-input-values-when-submitting-a-form) field elements after the Action succeeds. See [Preserving form values after submission](#preserve-form-values-after-submission).
51
+
* If you pass a function to `action` or `formAction`, React resets all [uncontrolled](/reference/react-dom/components/input#reading-the-input-values-when-submitting-a-form) field elements after the Action succeeds. See [Preserving form values after an Action](#preserve-form-values-after-an-action).
52
52
53
53
---
54
54
@@ -101,7 +101,7 @@ When you pass a function to `action`, React:
101
101
* Runs the function in a [Transition](/reference/react/useTransition), keeping the page responsive.
102
102
* Makes the pending state available to child components via [`useFormStatus`](/reference/react-dom/hooks/useFormStatus).
103
103
* Propagates any errors to the nearest Error Boundary.
104
-
* Resets the form's uncontrolled fields when the function succeeds. To keep their values, see [Preserving form values after submission](#preserve-form-values-after-submission).
104
+
* Resets the form's uncontrolled fields when the function succeeds. To keep their values, see [Preserving form values after an Action](#preserve-form-values-after-an-action).
105
105
106
106
Because the Action runs in a Transition, you can also use [`useActionState`](/reference/react/useActionState) to manage form state and [`useOptimistic`](/reference/react/useOptimistic) for optimistic UI. For [Server Functions](/reference/rsc/server-functions) and progressive enhancement, see [Handling form submission with a Server Function](#handle-form-submission-with-a-server-function).
107
107
@@ -385,27 +385,39 @@ If the form is submitted before JavaScript loads, React includes the Server Func
385
385
386
386
---
387
387
388
-
### Preserving form values after submission {/*preserve-form-values-after-submission*/}
388
+
### Preserving form values after an Action {/*preserve-form-values-after-an-action*/}
389
389
390
-
Submitting a form with a URL `action`clears its input state. React mirrors this behavior when `action` is a function by resetting the form's [uncontrolled fields](/reference/react-dom/components/input#reading-the-input-values-when-submitting-a-form) after the Action succeeds. When a Server Function progressively enhances a form, this keeps its behavior consistent before and after JavaScript loads. [Inputs controlled with state](/reference/react-dom/components/input#controlling-an-input-with-a-state-variable) are not cleared.
390
+
When you pass a function to `action`or `formAction`, React resets the form's [uncontrolled fields](/reference/react-dom/components/input#reading-the-input-values-when-submitting-a-form) after the Action succeeds. To keep the submitted values, store each value in state and pass it to that field's `defaultValue`. The reset then restores each field to its `defaultValue` instead of clearing it.
391
391
392
-
#### Restore fields with `useActionState` {/*with-useactionstate*/}
392
+
To keep those values when users submit the form before JavaScript loads, render the `<form>` from a [Client Component](/reference/rsc/use-client) and pass a [Server Function](/reference/rsc/server-functions) to [`useActionState`](/reference/react/useActionState). Pass the Action it returns to the form's `action` prop. The Server Function receives the previous state, followed by the submitted `FormData`, as shown in [Displaying a form submission error without JavaScript](#display-a-form-submission-error-without-javascript). Return an object with the values to keep, and pass each value, such as `state.title`, to the matching field's `defaultValue`:
393
393
394
-
Pass the Action returned by [`useActionState`](/reference/react/useActionState) to the `action` prop. Return the values you want to keep from your Action, and pass them to each field's `defaultValue`. The automatic form reset restores those default values instead of clearing the fields.
Users can submit the form before JavaScript loads. After the Action succeeds, `defaultValue={state.title}` restores the title from the returned object.
431
+
432
+
For a form that submits only after JavaScript loads, store the values with [`useState`](/reference/react/useState). Update that state when the Action finishes. React applies the new `defaultValue`, then resets the form, so each field shows the submitted value:
433
+
434
+
<Sandpack>
435
+
436
+
```js src/App.js
437
+
import { useState } from'react';
438
+
439
+
exportdefaultfunctionEditForm() {
440
+
const [title, setTitle] =useState('My draft');
441
+
442
+
asyncfunctionsaveAction(formData) {
443
+
awaitnewPromise((res) =>setTimeout(res, 1000));
444
+
setTitle(formData.get('title'));
445
+
}
446
+
447
+
return (
448
+
<form action={saveAction}>
449
+
<input name="title" defaultValue={title} />
450
+
<button type="submit">Save</button>
451
+
</form>
452
+
);
424
453
}
425
454
```
426
455
427
456
</Sandpack>
428
457
458
+
Call a Server Function from `saveAction`, then store the string it returns. Because `saveAction` is defined in the Client Component, users can submit this form only after JavaScript loads:
459
+
460
+
```js
461
+
// actions.js
462
+
'use server';
463
+
464
+
import { saveTitle } from'./api.js';
465
+
466
+
exportasyncfunctionsubmitTitle(formData) {
467
+
consttitle=formData.get('title');
468
+
awaitsaveTitle(title);
469
+
return title;
470
+
}
471
+
```
472
+
473
+
```js
474
+
// EditForm.js
475
+
'use client';
476
+
477
+
import { useState } from'react';
478
+
import { submitTitle } from'./actions.js';
479
+
480
+
exportdefaultfunctionEditForm() {
481
+
const [title, setTitle] =useState('My draft');
482
+
483
+
asyncfunctionsaveAction(formData) {
484
+
constsavedTitle=awaitsubmitTitle(formData);
485
+
setTitle(savedTitle);
486
+
}
487
+
488
+
return (
489
+
<form action={saveAction}>
490
+
<input name="title" defaultValue={title} />
491
+
<button type="submit">Save</button>
492
+
</form>
493
+
);
494
+
}
495
+
```
496
+
429
497
<DeepDive>
430
498
431
-
#### Choosing how to manage form values {/*choosing-how-to-manage-form-values*/}
499
+
#### Other ways to control form resets {/*other-ways-to-control-form-resets*/}
432
500
433
-
Choose an approach based on what should happen after submission:
501
+
The examples above keep every submitted value by storing it before the reset. You can also choose which values survive, or when the reset runs:
434
502
435
-
***Preserve selected values with `useActionState`.**The example above returns the submitted title after every submission. To preserve values only when validation fails, return the submitted `FormData`in the error state and use it to set each field's `defaultValue`. With a Server Function, React can include those values in the server response before JavaScript loads.
503
+
***Keep values only when validation fails.**Return the same state shape from every submission. When validation fails, include the submitted `FormData` and read each field with `state.submitted?.get('title') ?? ''`. When validation succeeds, set that `FormData` to `null` so the reset clears those fields. [`useActionState`](/reference/react/useActionState#displaying-validation-errors-and-preserving-form-values) shows this pattern.
436
504
437
-
***Keep every value with `onSubmit`.**Call `e.preventDefault()`, then run the Action inside [`startTransition`](/reference/react/useTransition). Calling `preventDefault()` prevents the function passed to the form's `action`prop from running for that submission, so React does not automatically reset the form.
505
+
***Skip the reset with `onSubmit`.**Handle the submission in `onSubmit`, call `e.preventDefault()`, and run the Action inside [`startTransition`](/reference/react/useTransition). Because the form's `action`does not run, React does not reset the form. Users can submit this form only after JavaScript loads.
438
506
439
-
***Reset fields at a specific point.** Call the form element's [`reset()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset) method to immediately reset uncontrolled fields to their default values. To schedule the same reset inside an Action or Transition, call [`requestFormReset`](/blog/2024/12/05/react-19#form-actions) from `react-dom`.
507
+
***Reset at a specific moment.** Call the form element's [`reset()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/reset) method to immediately reset uncontrolled fields to their default values. To schedule a reset as part of an Action or Transition, call [`requestFormReset`](/blog/2024/12/05/react-19#form-actions) from `react-dom` instead.
440
508
441
-
***Reset the fields and component state.** Change the [`key`](/learn/preserving-and-resetting-state#resetting-a-form-with-a-key)on the component that renders the form. React recreates the component and its DOM, so its fields and local state both start over.
509
+
***Reset the form and the component state together.** Change the [`key`](/learn/preserving-and-resetting-state#resetting-a-form-with-a-key)of the component that renders the form. React recreates the component and its DOM, which resets the fields and any local state.
0 commit comments