new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

React · API reference · all subjects

react-dom/components/form

100 notes in this subject, read out of this brain and free to use. This is page 2 of 2.

<option> value prop

The value prop specifies the value to be used when submitting the parent <select> in a form if this option is selected.

<option> label prop

The label prop is a string that specifies the meaning of the option. If not specified, the text inside the option element is used as the label.

<select> example: basic select box

```js export default function FruitPicker() { return ( <label> Pick a fruit: <select name="selectedFruit"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> ); } ``` This example shows how to render a basic uncontrolled select box with a label and three options.

<select> props: value and onChange

To create a controlled select box, pass a value prop (a string or array of strings for multiple={true}) to control which option is selected. You must also pass an onChange handler that updates the backing value. The onChange fires immediately when the user picks a different option.

<select> props: defaultValue

For uncontrolled select boxes, pass defaultValue as a string (or array of strings for multiple={true}) to specify the initially selected option. Do not use the defaultValue prop if the select box is controlled via the value prop.

<select> props: autoComplete

autoComplete is a string prop that specifies one of the possible autocomplete behaviors as documented in the MDN autocomplete values reference.

<select> props: autoFocus

autoFocus is a boolean prop. If true, React will focus the element on mount.

<select> props: multiple

multiple is a boolean prop. If true, the browser allows multiple selection. When enabled, the value and defaultValue props must be arrays of strings instead of single strings.

<select> props: name

name is a string prop that specifies the name for the select box. This name is used when submitting the form and becomes the key in form data (e.g., { selectedFruit: "orange" }).

<select> props: required

required is a boolean prop. If true, a value must be provided for the form to submit.

<select> props: size

size is a number prop. For multiple={true} selects, it specifies the preferred number of initially visible items.

<select> caveat: selected attribute not supported

Unlike in HTML, passing a selected attribute to <option> is not supported in React. Instead, use <select defaultValue> for uncontrolled select boxes or <select value> for controlled select boxes.

<select> caveat: value prop makes it controlled

If a select box receives a value prop, it will be treated as controlled. A controlled select box must have an onChange handler to update the value, and it cannot switch between controlled and uncontrolled modes over its lifetime.

<select> caveat: cannot be both controlled and uncontrolled

A select box cannot be both controlled and uncontrolled at the same time, and it cannot switch between being controlled or uncontrolled over its lifetime.

<select> caveat: controlled without onChange

If you pass value without onChange, it will be impossible to select an option. When you control a select box by passing some value, React will revert the select box back to that value after every keystroke if the state is not synchronously updated in the onChange handler.

<select> example: with defaultValue

```js export default function FruitPicker() { return ( <label> Pick a fruit: <select name="selectedFruit" defaultValue="orange"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> ); } ``` This example shows how to set an initially selected option by passing defaultValue to an uncontrolled select box.

<select> example: multiple selection with defaultValue

```js export default function FruitPicker() { return ( <label> Pick some fruits: <select name="selectedFruit" defaultValue={['orange', 'banana']} multiple={true} > <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> ); } ``` This example shows how to enable multiple selection with multiple={true} and set initially selected options using an array for defaultValue.

<select> example: controlled single select

```js import { useState } from 'react'; function FruitPicker() { const [selectedFruit, setSelectedFruit] = useState('orange'); return ( <select value={selectedFruit} onChange={e => setSelectedFruit(e.target.value)} > <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> ); } ``` This example shows how to create a controlled select box using useState to manage the selected value.

<select> example: controlled multiple select

```js import { useState } from 'react'; export default function FruitPicker() { const [selectedVegs, setSelectedVegs] = useState(['corn', 'tomato']); return ( <label> Pick all your favorite vegetables: <select multiple={true} value={selectedVegs} onChange={e => { const options = [...e.target.selectedOptions]; const values = options.map(option => option.value); setSelectedVegs(values); }} > <option value="cucumber">Cucumber</option> <option value="corn">Corn</option> <option value="tomato">Tomato</option> </select> </label> ); } ``` This example shows how to create a controlled select box with multiple={true}. The onChange handler uses e.target.selectedOptions to get all selected values as an array.

<select> example: reading form data on submit

```js export default function EditPost() { function handleSubmit(e) { e.preventDefault(); const form = e.target; const formData = new FormData(form); fetch('/some-api', { method: form.method, body: formData }); console.log(new URLSearchParams(formData).toString()); const formJson = Object.fromEntries(formData.entries()); console.log(formJson); // Note: doesn't include multiple select values console.log([...formData.entries()]); } return ( <form method="post" onSubmit={handleSubmit}> <label> Pick your favorite fruit: <select name="selectedFruit" defaultValue="orange"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> <label> Pick all your favorite vegetables: <select name="selectedVegetables" multiple={true} defaultValue={['corn', 'tomato']} > <option value="cucumber">Cucumber</option> <option value="corn">Corn</option> <option value="tomato">Tomato</option> </select> </label> <button type="submit">Submit</button> </form> ); } ``` This example shows how to read select box values when a form is submitted. For multiple selects, use FormData entries or [...formData.entries()] to get all selected values.

<select> form submission note about name attribute

The name attribute on a <select> element is used as the key in form data. For example, <select name="selectedFruit" /> will produce form data like { selectedFruit: "orange" }. For multiple selects, FormData will include each selected value as a separate name-value pair.

<select> with useId for label association

When you cannot nest <select> inside a <label>, associate them by passing the same ID to <select id> and <label htmlFor>. Use useId to generate unique IDs to avoid conflicts between multiple instances of a component.

<select> props: children

The <select> component accepts <option>, <optgroup>, and <datalist> components as children. You can also pass your own components as long as they eventually render one of the allowed components. If you pass custom components that render <option> tags, each <option> must have a value prop.

<select> props: disabled

disabled is a boolean prop. If true, the select box will not be interactive and will appear dimmed.

<select> props: form

form is a string prop that specifies the id of the <form> element this select box belongs to. If omitted, the select box belongs to the closest parent form.

textarea pitfall: value without onChange

If you pass value without onChange, it will be impossible to type into the textarea. When you control a textarea by passing some value to it, you force it to always have that value. If you forget to update the state variable synchronously during the onChange event handler, React will revert the textarea after every keystroke back to the value you specified. You will see a console error: 'You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field.'

textarea caveats about controlled vs uncontrolled

Passing children to textarea like <textarea>something</textarea> is not allowed. If a textarea receives a string value prop, it will be treated as controlled. A textarea cannot be both controlled and uncontrolled at the same time. A textarea cannot switch between being controlled or uncontrolled over its lifetime. Every controlled textarea needs an onChange event handler that synchronously updates its backing value.

textarea component basic usage

The textarea component is a built-in browser component that lets you render a multiline text input. Render it with <textarea />.

textarea requires name prop for form submission

Give a name to your textarea, for example <textarea name="postContent" />. The name you specified will be used as a key in the form data, for example { postContent: "Your post" }.

textarea pitfall: caret jumps to beginning

If you control a textarea, you must update its state variable to the textarea's value from the DOM during onChange. You must update it to e.target.value synchronously, not to something else like e.target.value.toUpperCase() or asynchronously with setTimeout. If the textarea gets removed and re-added from the DOM on every keystroke, the caret will jump. This can happen if the textarea always receives a different key attribute or if you nest component definitions (which causes the inner component to remount on every render).

textarea props reference

The textarea component supports all common element props. Additionally, it accepts the following specific props: value (string, controls text inside for controlled textarea), defaultValue (string, specifies initial value for uncontrolled textarea), autoComplete ('on' or 'off'), autoFocus (boolean), cols (number, default 20), disabled (boolean), form (string, id of form this input belongs to), maxLength (number), minLength (number), name (string), onChange (event handler, required for controlled textareas, fires on every keystroke), onChangeCapture (capture phase version of onChange), onInput (event handler, fires when value changes), onInputCapture (capture phase version of onInput), onInvalid (event handler, fires if input fails validation, bubbles), onInvalidCapture (capture phase version of onInvalid), onSelect (event handler, fires after selection changes), onSelectCapture (capture phase version of onSelect), placeholder (string), readOnly (boolean), required (boolean), rows (number, default 2), wrap ('hard', 'soft', or 'off'). The children prop is not accepted; use defaultValue for initial content instead.

textarea pitfall: children not supported

Unlike in HTML, passing initial text like <textarea>Some content</textarea> is not supported in React. Use the defaultValue prop for initial content instead.

textarea with label and useId

Example of associating a textarea with a label using useId: import { useId } from 'react'; export default function Form() { const postTextAreaId = useId(); return ( <> <label htmlFor={postTextAreaId}> Write your post: </label> <textarea id={postTextAreaId} name="postContent" rows={4} cols={40} /> </> ); }

textarea uncontrolled example with defaultValue

Example of an uncontrolled textarea with initial value: export default function EditPost() { return ( <label> Edit your post: <textarea name="postContent" defaultValue="I really enjoyed biking yesterday!" rows={4} cols={40} /> </label> ); }

textarea controlled example with useState

Example of a controlled textarea using React state: function NewPost() { const [postContent, setPostContent] = useState(''); return ( <textarea value={postContent} onChange={e => setPostContent(e.target.value)} /> ); }

textarea with form submission

Example of reading textarea value when submitting a form: export default function EditPost() { function handleSubmit(e) { e.preventDefault(); const form = e.target; const formData = new FormData(form); fetch('/some-api', { method: form.method, body: formData }); const formJson = Object.fromEntries(formData.entries()); console.log(formJson); } return ( <form method="post" onSubmit={handleSubmit}> <label> Edit your post: <textarea name="postContent" defaultValue="I really enjoyed biking yesterday!" rows={4} cols={40} /> </label> <button type="submit">Save post</button> </form> ); }

textarea pitfall: switching between controlled and uncontrolled

If you get the error 'A component is changing an uncontrolled input to be controlled', it means you are passing value that changes between undefined/null and a string. You cannot pass value={undefined} first and later pass value="some string" because React won't know whether you want the component to be uncontrolled or controlled. A controlled component should always receive a string value, not null or undefined. If your value is coming from an API or state variable initialized to null or undefined, either set it to an empty string initially, or pass value={someValue ?? ''} to ensure value is a string.

useFormStatus example usage

Example of useFormStatus: In a Button component, destructure the pending property from useFormStatus() and use it to disable a submit button while a form action is processing. The button is disabled when pending is true and enabled when pending is false.

useFormStatus Hook returns pending status

The useFormStatus Hook returns an object with a pending property that indicates whether a form action is in progress.

useFormStatus Hook purpose

The useFormStatus Hook allows you to make updates to the UI based on the status of a form.

Give your agent this brain