From 4b333ca000cdd14e6704fe1443f7286d654f859e Mon Sep 17 00:00:00 2001 From: Matt Carroll <7158882+mattcarrollcode@users.noreply.github.com> Date: Thu, 26 Oct 2023 15:22:37 -0700 Subject: [PATCH] Add
Component reference documentation (#6312) Co-authored-by: Luna --- .../reference/react-dom/components/form.md | 435 ++++++++++++++++++ .../reference/react-dom/components/input.md | 7 + src/sidebarReference.json | 5 + 3 files changed, 447 insertions(+) create mode 100644 src/content/reference/react-dom/components/form.md diff --git a/src/content/reference/react-dom/components/form.md b/src/content/reference/react-dom/components/form.md new file mode 100644 index 000000000..b04793032 --- /dev/null +++ b/src/content/reference/react-dom/components/form.md @@ -0,0 +1,435 @@ +--- +title: "" +canary: true +--- + + + +React's extensions to `` are currently only available in React's canary and experimental channels. In stable releases of React `` works only as a [built-in browser HTML component](https://react.dev/reference/react-dom/components#all-html-components). Learn more about [React's release channels here](/community/versioning-policy#all-release-channels). + + + + + + +The [built-in browser `` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) lets you create interactive controls for submitting information. + +```js + + + + +``` + + + + + +--- + +## Reference {/*reference*/} + +### `
` {/*form*/} + +To create interactive controls for submitting information, render the [built-in browser `` component](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form). + +```js + + + +
+``` + +[See more examples below.](#usage) + +#### Props {/*props*/} + +`
` supports all [common element props.](/reference/react-dom/components/common#props) + +[`action`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#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](https://developer.mozilla.org/en-US/docs/Web/API/FormData) of the submitted form. The `action` prop can be overridden by a `formAction` attribute on a ` +
+ ); +} +``` + +```json package.json hidden +{ + "dependencies": { + "react": "18.3.0-canary-6db7f4209-20231021", + "react-dom": "18.3.0-canary-6db7f4209-20231021", + "react-scripts": "^5.0.0" + }, + "main": "/index.js", + "devDependencies": {} +} +``` + + + +### Handle form submission with a Server Action {/*handle-form-submission-with-a-server-action*/} + +Render a `
` with an input and submit button. Pass a server action (a function marked with [`'use server'`](/reference/react/use-server)) to the `action` prop of form to run the function when the form is submitted. + +Passing a server action to `` 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. + +You can use hidden form fields to provide data to the ``'s action. The server action will be called with the hidden form field data as an instance of [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData). + +```jsx +import { updateCart } from './lib.js'; + +function AddToCart({productId}) { + async function addToCart(formData) { + 'use server' + const productId = formData.get('productId') + await updateCart(productId) + } + return ( + + + +
+ + ); +} +``` + +In lieu of using hidden form fields to provide data to the `
`'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 a argument to the function. + +```jsx [[1, 8, "bind"], [2,8, "productId"], [2,4, "productId"], [3,4, "formData"]] +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 ( + + +
+ ); +} +``` + +When `
` is rendered by a [Server Component](/reference/react/use-client), and a [Server Action](/reference/react/use-server) is passed to the ``'s `action` prop, the form is [progressively enhanced](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement). + +### Display a pending state during form submission {/*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 `` and read the `pending` property returned. + +Here, we use the `pending` property to indicate the form is submitting. + + + +```js App.js +import { useFormStatus } from "react-dom"; +import { submitForm } from "./actions.js"; + +function Submit() { + const { pending } = useFormStatus(); + return ( + + ); +} + +function Form({ action }) { + return ( + + + + ); +} + +export default function App() { + return
; +} +``` + +```js actions.js hidden +export async function submitForm(query) { + await new Promise((res) => setTimeout(res, 1000)); +} +``` + +```json package.json hidden +{ + "dependencies": { + "react": "canary", + "react-dom": "canary", + "react-scripts": "^5.0.0" + }, + "main": "/index.js", + "devDependencies": {} +} +``` + + +To learn more about the `useFormStatus` Hook see the [reference documentation](/reference/react-dom/hooks/useFormStatus). + +### Optimistically updating form data {/*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. + + + + +```js App.js +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(); + await sendMessage(formData); + } + const [optimisticMessages, addOptimisticMessage] = useOptimistic( + messages, + (state, newMessage) => [ + ...state, + { + text: newMessage, + sending: true + } + ] + ); + + return ( + <> + {optimisticMessages.map((message, index) => ( +
+ {message.text} + {!!message.sending && (Sending...)} +
+ ))} + + + + + + ); +} + +export default function App() { + const [messages, setMessages] = useState([ + { text: "Hello there!", sending: false, key: 1 } + ]); + async function sendMessage(formData) { + const sentMessage = await deliverMessage(formData.get("message")); + setMessages([...messages, { text: sentMessage }]); + } + return ; +} +``` + +```js actions.js +export async function deliverMessage(message) { + await new Promise((res) => setTimeout(res, 1000)); + return message; +} +``` + + +```json package.json hidden +{ + "dependencies": { + "react": "18.3.0-canary-6db7f4209-20231021", + "react-dom": "18.3.0-canary-6db7f4209-20231021", + "react-scripts": "^5.0.0" + }, + "main": "/index.js", + "devDependencies": {} +} +``` + +
+ +[//]: # 'Uncomment the next line, and delete this line after the `useOptimisitc` reference documentatino page is published' +[//]: # 'To learn more about the `useOptimistic` Hook see the [reference documentation](/reference/react/hooks/useOptimistic).' + +### Handling form submission errors {/*handling-form-submission-errors*/} + +In some cases the function called by a `
`'s `action` prop throw an error. You can handle these errors by wrapping `` in an Error Boundary. If the function called by a ``'s `action` prop throws an error, the fallback for the error boundary will be displayed. + + + +```js App.js +import { ErrorBoundary } from "react-error-boundary"; + +export default function Search() { + function search() { + throw new Error("search error"); + } + return ( + There was an error while submitting the form

} + > + + + + +
+ ); +} + +``` + +```json package.json hidden +{ + "dependencies": { + "react": "18.3.0-canary-6db7f4209-20231021", + "react-dom": "18.3.0-canary-6db7f4209-20231021", + "react-scripts": "^5.0.0", + "react-error-boundary": "4.0.3" + }, + "main": "/index.js", + "devDependencies": {} +} +``` + +
+ +### Display a form submission error without JavaScript {/*display-a-form-submission-error-without-javascript*/} + +Displaying a form submission error message before the JavaScript bundle loads for progressive enhancement requires that: + +1. `
` be rendered by a [Server Component](/reference/react/use-client) +1. the function passed to the ``'s `action` prop be a [Server Action](/reference/react/use-server) +1. the `useFormState` Hook be used to display the error message + +`useFormState` takes two parameters: a [Server Action](/reference/react/use-server) and an inital state. `useFormState` returns two values, a state variable and an action. The action returned by `useFormState` should be passed to the `action` prop of the form. The state varible returned by `useFormState` can be used to displayed an error message. The value returned by the [Server Action](/reference/react/use-server) passed to `useFormState` will be used to update the state variable. + + + +```js App.js +import { useFormState } from "react-dom"; +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) { + return err.toString(); + } + } + const [message, formAction] = useFormState(signup, null); + return ( + <> +

Signup for my newsletter

+

Signup with the same email twice to see an error

+ + + + + {!!message &&

{message}

} + + + ); +} +``` + +```js api.js hidden +let emails = []; + +export async function signUpNewUser(newEmail) { + if (emails.includes(newEmail)) { + throw new Error("This email address has already been added"); + } + emails.push(newEmail); +} +``` + +```json package.json hidden +{ + "dependencies": { + "react": "18.3.0-canary-6db7f4209-20231021", + "react-dom": "18.3.0-canary-6db7f4209-20231021", + "react-scripts": "^5.0.0" + }, + "main": "/index.js", + "devDependencies": {} +} +``` + +
+ +Learn more about updating state from a form action with the [`useFormState`](/reference/react-dom/hooks/useFormState) docs + +### Handling multiple submission types {/*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 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 seperate button with `formAction` set to save the article as a draft. + + + +```js App.js +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!`); + } + + return ( +
+