Skip to content

Commit 3a784ea

Browse files
Clarify form submission handling and examples
Updated the form submission section to clarify how to prevent unwanted form resets and provided an example using controlled inputs with React state.
1 parent abe931a commit 3a784ea

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

  • src/content/reference/react-dom/components

src/content/reference/react-dom/components/form.md

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -48,26 +48,34 @@ To create interactive controls for submitting information, render the [built-in
4848

4949
## Usage {/*usage*/}
5050

51-
### Handle form submission on the client {/*handle-form-submission-on-the-client*/}
51+
### Preventing unwanted form reset
5252

53-
Pass a function to the `action` prop of form to run the function when the form is submitted. [`formData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) will be passed to the function as an argument so you can access the data submitted by the form. This differs from the conventional [HTML action](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#action), which only accepts URLs. After the `action` function succeeds, all uncontrolled field elements in the form are reset.
53+
When a function is passed to the `action` prop, uncontrolled form fields are automatically reset after a successful submission.
5454

55-
<Sandpack>
55+
If you need to preserve the form input values, you can control the inputs using React state or use `onSubmit` with `event.preventDefault()`.
5656

57-
```js src/App.js
58-
export default function Search() {
59-
function search(formData) {
60-
const query = formData.get("query");
61-
alert(`You searched for '${query}'`);
57+
```jsx
58+
import { useState } from "react";
59+
60+
export default function Form() {
61+
const [value, setValue] = useState("");
62+
63+
function handleSubmit(e) {
64+
e.preventDefault();
65+
// handle submit without resetting input
6266
}
67+
6368
return (
64-
<form action={search}>
65-
<input name="query" />
66-
<button type="submit">Search</button>
69+
<form onSubmit={handleSubmit}>
70+
<input
71+
name="query"
72+
value={value}
73+
onChange={(e) => setValue(e.target.value)}
74+
/>
75+
<button type="submit">Submit</button>
6776
</form>
6877
);
6978
}
70-
```
7179

7280
</Sandpack>
7381

0 commit comments

Comments
 (0)