Skip to content

Commit 79b7bad

Browse files
Add guidance on preventing form reset in React
Added section on preventing unwanted form reset during submission. Included example using React state and event.preventDefault().
1 parent abe931a commit 79b7bad

File tree

1 file changed

+28
-0
lines changed
  • src/content/reference/react-dom/components

1 file changed

+28
-0
lines changed

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,34 @@ To create interactive controls for submitting information, render the [built-in
5050

5151
### Handle form submission on the client {/*handle-form-submission-on-the-client*/}
5252

53+
### Preventing unwanted form reset {/*preventing-form-reset*/}
54+
55+
When a function is passed to the `action` prop, uncontrolled form fields are automatically reset after a successful submission.
56+
57+
If you need to preserve the form input values, you can control the inputs using React state or use `onSubmit` with `event.preventDefault()`.
58+
59+
```jsx
60+
import { useState } from "react";
61+
62+
export default function Form() {
63+
const [value, setValue] = useState("");
64+
65+
function handleSubmit(e) {
66+
e.preventDefault();
67+
}
68+
69+
return (
70+
<form onSubmit={handleSubmit}>
71+
<input
72+
name="query"
73+
value={value}
74+
onChange={(e) => setValue(e.target.value)}
75+
/>
76+
<button type="submit">Submit</button>
77+
</form>
78+
);
79+
}
80+
5381
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.
5482

5583
<Sandpack>

0 commit comments

Comments
 (0)