Functional Weave
Code in Rust

react.form.checkbox@1.0.1

README.md

2,896 bytes · view raw

# react.form.checkbox

One checkbox on its own, with its label to the right of the box: "I agree to
the terms", "Remember me on this device", "Send me news by email". It is the
GOV.UK Design System checkbox used to toggle a single option on or off, with
an optional hint under the label and an error message above the box.

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

<Checkbox id="terms" label="I agree to the terms and conditions" required
  error={errors.terms} checked={agreed} onChange={setAgreed} />
```

- **onChange** is called with `true` when the box is ticked and `false` when
  it is cleared, not with the event.
- **checked** with **onChange** is a controlled checkbox; **defaultChecked**
  alone is an uncontrolled one, fine for a plain `<form>` post. Do not pass
  both.
- **onBlur** is called, with nothing, when the box loses focus, so a form
  can mark the field touched (`form.state`'s blur action).
- **value** is what the form posts when the box is ticked. It is `yes` when
  left out, rather than the browser's `on`, so a server reads `terms=yes`;
  nothing at all is posted when the box is clear. `""` is kept as `""`.
- **id** is the checkbox's id and, unless **name** says otherwise, the name it
  is posted under. Left out, it is React's `useId()`; pass one whenever an
  error summary has to link to the box.

Why not `FormField`: its label comes before the control, and a checkbox's
label goes after the box, so this component takes the same ids from
`fieldIds` (`<id>-hint`, `<id>-error`, described hint first) and lays them out
itself. Unlike a box in a `react.form.checkbox-group`, a lone checkbox is a
control of its own, so the error describes the input and marks it
`aria-invalid="true"`. The hint goes under the label, where GOV.UK puts an
item hint.

For several related choices use `react.form.checkbox-group`; for a yes or no
answer that must be given either way, use `react.form.radio-group` with Yes
and No, since an unticked box cannot tell "no" from "did not answer".

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

Classes: `fune-field` (and `fune-field--error`), `fune-error-message`,
`fune-visually-hidden`, `fune-checkbox` (the box and its label),
`fune-checkbox-input`, `fune-label fune-checkbox-label`,
`fune-hint fune-checkbox-hint`.

Sources: GOV.UK Design System, "Checkboxes" (toggling a single option, item
hints) https://design-system.service.gov.uk/components/checkboxes/ and "Error
message" https://design-system.service.gov.uk/components/error-message/.

## 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.