Functional Weave
Code in TypeScript

react.form.select@1.0.1

README.md

2,880 bytes · view raw

# react.form.select

A drop-down list with its label, an optional hint and error message, and the
accessible wiring done: the label's `for`, the select's `aria-describedby`
(hint, then error) and `aria-invalid` when there is an error. It is the
GOV.UK Design System select, built on `react.form.form-field`.

**Try not to use it.** GOV.UK: "Before using the select component, try
asking users questions which will allow you to present them with fewer
options", and then use radios (`react.form.radio-group`). Selects are hard
for many people to use, hide the options until opened, and are awkward on a
phone. Keep this for long lists a person knows the answer to, such as a
country, or for sorting a list of results.

```tsx
"use client";
import { Select } from "#fune/react.form.select@^1";

<Select id="sort" label="Sort by" value={sort} onChange={setSort}
  options={[
    { value: "published", label: "Recently published" },
    { value: "updated", label: "Recently updated" },
    { value: "views", label: "Most views" },
  ]} />
```

- **placeholder** adds a first option with the value `""` ("Choose a
  country"). With **required**, the browser refuses the form until something
  else is chosen, and a post without a choice arrives as an empty value.
  An option of its own with the value `""` beside a placeholder is refused.
- **onChange** is called with the chosen value, not the event. **value**
  with onChange is controlled; **defaultValue** alone is uncontrolled. React
  renders the chosen option as `selected`; a value that is no option selects
  nothing, so the browser shows the first.
- **onBlur** is called, with nothing, when the select loses focus, so a form
  can mark the field touched (`form.state`'s blur action).
- **Option labels are text** (`string`, not a node): an `<option>` cannot hold
  markup, and React warns if it is given an element.
- **autoComplete** takes the HTML token, such as `country`, so a browser can
  fill it.
- **id** is the select's id and, unless **name** says otherwise, the name it
  posts under; React's `useId()` when left out.
- Option values must be unique (they are the React keys).

It is a client component (it listens for changes), so the built file starts
with `"use client"`.

Classes: those of `react.form.form-field`, plus `fune-select` (and
`fune-select--error`).

Sources: GOV.UK Design System, "Select" (markup, error state, and the advice
to ask questions that allow radios instead)
https://design-system.service.gov.uk/components/select/ and "Radios"
https://design-system.service.gov.uk/components/radios/.

## Notices

Portions derived from GOV.UK Frontend (https://github.com/alphagov/govuk-frontend), Copyright (c) 2017 Crown Copyright (Government Digital Service), under the MIT License; the full notice is in NOTICE.

1.0.1 adds its attribution notices (NOTICE). The code and the tests are unchanged.