Skip to content

Add example around disabling default form reset behaviour #7795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/content/reference/react-dom/components/form.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,39 @@ export default function Search() {

</Sandpack>

You can override the default reset behaviour of the form by additionally passing an `onSubmit` prop to the `<form>` component calls `preventDefault` on the event and calling the action yourself. Passing `onSubmit` alongside `action` ensures the form can be progressively enhanced if this component is rendered to HTML on the server.

Notice how in the below example now the form is not reset and your input is preserved after the form is submitted.

<Sandpack>

```js
import { startTransition } from "react";
export default function Search() {
function search(formData) {
const query = formData.get("query");
alert(`You searched for '${query}'`);
}
return (
<form
action={search}
onSubmit={(event) => {
event.preventDefault();
const formData = new FormData(event.currentTarget);
startTransition(() => {
search(formData);
});
}}
>
<input name="query" />
<button type="submit">Search</button>
</form>
);
}
```

</Sandpack>

### Handle form submission with a Server Function {/*handle-form-submission-with-a-server-function*/}

Render a `<form>` with an input and submit button. Pass a Server Function (a function marked with [`'use server'`](/reference/rsc/use-server)) to the `action` prop of form to run the function when the form is submitted.
Expand Down