0% found this document useful (0 votes)
8 views

_form_ – React

The document provides an overview of the built-in <form> component in React, detailing its usage for creating interactive controls for form submissions. It covers various functionalities such as handling submissions with client-side functions, server functions, displaying pending states, optimistically updating data, and managing errors. Additionally, it explains how to handle multiple submission types based on user interaction with different buttons within the form.

Uploaded by

dungeon.dad87
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

_form_ – React

The document provides an overview of the built-in <form> component in React, detailing its usage for creating interactive controls for form submissions. It covers various functionalities such as handling submissions with client-side functions, server functions, displaying pending states, optimistically updating data, and managing errors. Additionally, it explains how to handle multiple submission types based on user interaction with different buttons within the form.

Uploaded by

dungeon.dad87
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

20/02/2025, 10:01 <form> – React

v19

API REFERENCE COMPONENTS

<form>
The built-in browser <form> component lets you create
interactive controls for submitting information.

<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>

Reference

<form>

Usage

Handle form submission on the client


Handle form submission with a Server Function
Display a pending state during form submission
Optimistically updating form data
Handling form submission errors
Display a form submission error without JavaScript
Handling multiple submission types

Reference

<form>

To create interactive controls for submitting information, render the built-in


browser <form> component.

https://react.dev/reference/react-dom/components/form 1/11
20/02/2025, 10:01 <form> – React

<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>

See more examples below.

Props

<form> supports all common element props.

action : a URL or function. When a URL is passed to action the form will

behave like the HTML form component. When a function is passed to


action the function will handle the form submission. The function passed to

action may be async and will be called with a single argument containing

the form data of the submitted form. The action prop can be overridden by
a formAction attribute on a <button> , <input type="submit"> , or <input
type="image"> component.

Caveats

When a function is passed to action or formAction the HTTP method


will be POST regardless of value of the method prop.

Usage

Handle form submission on the client

Pass a function to the action prop of form to run the function when the
form is submitted. 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, which only accepts URLs. After the action
function succeeds, all uncontrolled field elements in the form are reset.

App.js Download Reset

https://react.dev/reference/react-dom/components/form 2/11
20/02/2025, 10:01 <form> – React

export default function Search() {


function search(formData) {
const query = formData.get("query");
alert(`You searched for '${query}'`);
}
return (
<form action={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
);
}

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' ) to the action prop of form to run the
function when the form is submitted.

Passing a Server Function to <form action> allow users to submit forms


without JavaScript enabled or before the code has loaded. This is beneficial
to users who have a slow connection, device, or have JavaScript disabled and
is similar to the way forms work when a URL is passed to the action prop.
https://react.dev/reference/react-dom/components/form 3/11
20/02/2025, 10:01 <form> – React

You can use hidden form fields to provide data to the <form> ’s action. The
Server Function will be called with the hidden form field data as an instance
of FormData .

import { updateCart } from './lib.js';

function AddToCart({productId}) {
async function addToCart(formData) {
'use server'
const productId = formData.get('productId')
await updateCart(productId)
}
return (
<form action={addToCart}>
<input type="hidden" name="productId" value={productId} />
<button type="submit">Add to Cart</button>
</form>

);
}

In lieu of using hidden form fields to provide data to the <form> ’s action, you
can call the bind method to supply it with extra arguments. This will bind a
new argument ( productId ) to the function in addition to the formData
that is passed as an argument to the function.

import { updateCart } from './lib.js';

function AddToCart({productId}) {
async function addToCart( productId , formData ) {
"use server";
await updateCart(productId)
}
const addProductToCart = addToCart. bind (null, productId );
return (
<form action={addProductToCart}>
<button type="submit">Add to Cart</button>
</form>

https://react.dev/reference/react-dom/components/form 4/11
20/02/2025, 10:01 <form> – React

);
}

When <form> is rendered by a Server Component, and a Server Function is


passed to the <form> ’s action prop, the form is progressively enhanced.

Display a pending state during form submission

To display a pending state when a form is being submitted, you can call the
useFormStatus Hook in a component rendered in a <form> and read the

pending property returned.

Here, we use the pending property to indicate the form is submitting.

App.js Reset

import { useFormStatus } from "react-dom";


import { submitForm } from "./actions.js";

function Submit() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? "Submitting..." : "Submit"}
</button>
);
}

Show more

https://react.dev/reference/react-dom/components/form 5/11
20/02/2025, 10:01 <form> – React

To learn more about the useFormStatus Hook see the reference


documentation.

Optimistically updating form data

The useOptimistic Hook provides a way to optimistically update the user


interface before a background operation, like a network request, completes.
In the context of forms, this technique helps to make apps feel more
responsive. When a user submits a form, instead of waiting for the server’s
response to reflect the changes, the interface is immediately updated with
the expected outcome.

For example, when a user types a message into the form and hits the “Send”
button, the useOptimistic Hook allows the message to immediately appear
in the list with a “Sending…” label, even before the message is actually sent
to a server. This “optimistic” approach gives the impression of speed and
responsiveness. The form then attempts to truly send the message in the
background. Once the server confirms the message has been received, the
“Sending…” label is removed.

App.js actions.js Reset

import { useOptimistic, useState, useRef } from "react";


import { deliverMessage } from "./actions.js";

function Thread({ messages, sendMessage }) {


const formRef = useRef();
async function formAction(formData) {
addOptimisticMessage(formData.get("message"));
formRef.current.reset();

https://react.dev/reference/react-dom/components/form 6/11
20/02/2025, 10:01 <form> – React

await sendMessage(formData);
}

Show more

Handling form submission errors

In some cases the function called by a <form> ’s action prop throws an


error. You can handle these errors by wrapping <form> in an Error Boundary.
If the function called by a <form> ’s action prop throws an error, the fallback
for the error boundary will be displayed.

App.js Reset

import { ErrorBoundary } from "react-error-boundary";

export default function Search() {


function search() {
throw new Error("search error");
}
return (
<ErrorBoundary

https://react.dev/reference/react-dom/components/form 7/11
20/02/2025, 10:01 <form> – React

fallback={<p>There was an error while submitting the form</p>}


>
<form action={search}>

Show more

Display a form submission error without JavaScript

Displaying a form submission error message before the JavaScript bundle


loads for progressive enhancement requires that:

1. <form> be rendered by a Server Component


2. the function passed to the <form> ’s action prop be a Server Function
3. the useActionState Hook be used to display the error message

useActionState takes two parameters: a Server Function and an initial

state. useActionState returns two values, a state variable and an action. The
action returned by useActionState should be passed to the action prop of
the form. The state variable returned by useActionState can be used to
display an error message. The value returned by the Server Function passed
to useActionState will be used to update the state variable.

https://react.dev/reference/react-dom/components/form 8/11
20/02/2025, 10:01 <form> – React

App.js Reset

import { useActionState } from "react";


import { signUpNewUser } from "./api";

export default function Page() {


async function signup(prevState, formData) {
"use server";
const email = formData.get("email");
try {
await signUpNewUser(email);
alert(`Added "${email}"`);
} catch (err) {

Show more

Learn more about updating state from a form action with the
useActionState docs

Handling multiple submission types

Forms can be designed to handle multiple submission actions based on the


button pressed by the user. Each button inside a form can be associated with
https://react.dev/reference/react-dom/components/form 9/11
20/02/2025, 10:01 <form> – React

a distinct action or behavior by setting the formAction prop.

When a user taps a specific button, the form is submitted, and a


corresponding action, defined by that button’s attributes and action, is
executed. For instance, a form might submit an article for review by default
but have a separate button with formAction set to save the article as a draft.

App.js Download Reset

export default function Search() {


function publish(formData) {
const content = formData.get("content");
const button = formData.get("button");
alert(`'${content}' was published with the '${button}' button`);
}

function save(formData) {
const content = formData.get("content");
alert(`Your draft of '${content}' has been saved!`);
}

Show more

https://react.dev/reference/react-dom/components/form 10/11
20/02/2025, 10:01 <form> – React

PREVIOUS

Common (e.g. <div>)

NEXT

<input>

Copyright © Meta Platforms, Inc

uwu?

Learn React API Reference

Quick Start React APIs

Installation React DOM APIs

Describing the UI

Adding Interactivity

Managing State

Escape Hatches

Community More

Code of Conduct Blog

Meet the Team React Native

Docs Contributors Privacy

Acknowledgements Terms

https://react.dev/reference/react-dom/components/form 11/11

You might also like