# Choice controls

> Checkbox, CheckboxGroup, RadioGroup and Switch. Labels beside the control, descriptions and errors wired up, a 44px touch size, and booleans and arrays that reach your form and your server as real values. Built on Base UI.

Source: https://platform.azmara.io/docs/components/choice

Group: Inputs · Status: new · Added in @azmr/ui 0.16.0

## Usage

```tsx
import { Checkbox, CheckboxGroup, Radio, RadioGroup, Switch } from "@azmr/ui/choice";
```

```tsx
"use client";

import { Checkbox, Switch } from "@azmr/ui/choice";
import { useState } from "react";

export default function ChoiceBasic() {
  const [signed, setSigned] = useState(false);
  return (
    <div className="flex w-full max-w-sm flex-col gap-4">
      <Checkbox
        label="Customer has signed"
        description="Tick it once the signed quote is back."
        checked={signed}
        onCheckedChange={setSigned}
      />
      <Checkbox label="Send me a copy" defaultChecked />
      <Checkbox label="Select all" indeterminate />
      <Switch label="Email me about new invoices" description="At most one email a day." />
      <Switch label="Show archived clients" defaultChecked />
      <Checkbox label="Accept the terms" required error="You must accept to continue." />
      <Checkbox label="Not available on this plan" disabled />
    </div>
  );
}
```

`Checkbox` and `Switch` take a `label`, shown beside the control, and optionally a `description` under it, an `error`, and `required`. `checked` is a plain boolean and `onCheckedChange` gets a boolean. A control without a visible label needs an `aria-label` or `aria-labelledby`; the types insist on one of the three.

The label is part of the click target, so clicking it toggles the control. Labels and descriptions are rendered as text: markup in them is shown, never run.

### Indeterminate

A checkbox that is neither ticked nor unticked, such as "select all" over a partial selection, takes the separate `indeterminate` prop. It is not `checked="indeterminate"`: `checked` stays a boolean, so it round-trips through a form. Clicking an indeterminate checkbox ticks it.

## Groups

```tsx
"use client";

import { Checkbox, CheckboxGroup, Radio, RadioGroup } from "@azmr/ui/choice";
import { useState } from "react";

const PLANS = [
  { value: "starter", label: "Starter", description: "One user, up to 10 invoices a month." },
  { value: "team", label: "Team", description: "Five users and quotations." },
  { value: "business", label: "Business", description: "Unlimited users, priority support." },
];

const MODULES = [
  { value: "invoices", label: "Invoices" },
  { value: "quotations", label: "Quotations" },
  { value: "payroll", label: "Payroll", disabled: true, description: "Coming soon." },
  { value: "reports", label: "Reports" },
];

export default function ChoiceGroups() {
  const [plan, setPlan] = useState("team");
  const [modules, setModules] = useState<string[]>(["invoices"]);
  return (
    <div className="flex w-full max-w-md flex-col gap-8">
      <RadioGroup
        label="Plan"
        description="You can change it later."
        options={PLANS}
        value={plan}
        onValueChange={setPlan}
      />
      <RadioGroup label="Billing" orientation="horizontal" defaultValue="monthly">
        <Radio value="monthly" label="Monthly" />
        <Radio value="yearly" label="Yearly" description="Two months free." />
      </RadioGroup>
      <CheckboxGroup
        label="Modules"
        options={MODULES}
        selectAllLabel="Select all"
        value={modules}
        onValueChange={setModules}
      />
      <CheckboxGroup label="Notify me by" size="lg" defaultValue={["email"]}>
        <Checkbox value="email" label="Email" />
        <Checkbox value="sms" label="Text message" description="Standard rates apply." />
      </CheckboxGroup>
    </div>
  );
}
```

`RadioGroup` and `CheckboxGroup` are named by a legend (`label`) and take either `options`, an array of `{ value, label, description?, disabled? }`, or hand-written items for layouts `options` does not cover. `options` renders the same items you would write by hand, so the two behave identically. Give the group `options` or children, not both; the types enforce it. Only those four fields of an option are read.

A `RadioGroup` value is one string; a `CheckboxGroup` value is an array of strings, and values the group does not know (a stale selection from a server) are kept when others are toggled. `orientation="horizontal"` lays the radios out in a row; every arrow key still moves between them.

### Select all

`CheckboxGroup` with `options` and `selectAllLabel` adds a "select all" checkbox first. It shows indeterminate while only some options are ticked, ticks all, and unticks all. It never changes a disabled option. With hand-written items, add a `<Checkbox parent label="…" />` and pass `allValues`: every value in the group, disabled ones included, since select all leaves a disabled checkbox as it is.

## Sizes and touch

`size` is `sm`, `md` (the default, following the density tokens) or `lg`. `lg` makes the whole label row at least 44px tall, which is a comfortable touch target, without enlarging the visible box. Set `size` on a group and every item follows it; an item can set its own.

## With react-hook-form

`FormField` binds these controls for you. They are controlled fields: a checkbox or switch holds a boolean, a radio group one string, a checkbox group a string array, and a field with no value yet is unchecked, `""` or `[]`. The control shows its own label, description and error, so give those to the control (or to `FormField`, which passes them on and wins if both are set). With `mode: "onBlur"` or `"onTouched"`, a group is validated when focus leaves it, not as it moves between its boxes.

```tsx
"use client";

import { Button } from "@azmr/ui/button";
import { Checkbox, CheckboxGroup, RadioGroup, Switch } from "@azmr/ui/choice";
import { Form, FormField } from "@azmr/ui/rhf";
import { zodResolver } from "@azmr/ui/zod";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";

const schema = z.object({
  plan: z.enum(["starter", "team"], "Pick a plan"),
  modules: z
    .array(z.enum(["invoices", "quotations", "reports"]))
    .min(1, "Pick at least one module"),
  notify: z.boolean(),
  terms: z.boolean().refine((accepted) => accepted, "You must accept the terms"),
});

type Input = z.input<typeof schema>;

export default function ChoiceForm() {
  const [saved, setSaved] = useState<unknown>();
  const form = useForm<Input>({
    resolver: zodResolver(schema),
    // No default for `plan`: a field with no value yet shows nothing chosen.
    defaultValues: { modules: [], notify: false, terms: false },
    shouldFocusError: false,
  });
  return (
    <Form form={form} onSubmit={setSaved} className="flex w-full max-w-md flex-col gap-6">
      <FormField name="plan">
        <RadioGroup
          label="Plan"
          options={[
            { value: "starter", label: "Starter" },
            { value: "team", label: "Team" },
          ]}
        />
      </FormField>
      <FormField name="modules">
        <CheckboxGroup
          label="Modules"
          options={[
            { value: "invoices", label: "Invoices" },
            { value: "quotations", label: "Quotations" },
            { value: "reports", label: "Reports" },
          ]}
        />
      </FormField>
      <FormField name="notify">
        <Switch label="Email me about new invoices" />
      </FormField>
      <FormField name="terms">
        <Checkbox label="I accept the terms" />
      </FormField>
      <Button type="submit">Save</Button>
      {saved ? (
        <pre className="rounded-md bg-muted p-3 text-xs">{JSON.stringify(saved, null, 2)}</pre>
      ) : null}
    </Form>
  );
}
```

```tsx
<FormField name="terms">
  <Checkbox label="I accept the terms" />
</FormField>
```

Use `z.literal(true)` (or a boolean with a `refine`) for a "must accept" box, and a `z.enum` or `z.array(z.enum(...))` for choices. In `fieldsFromSchema`, a boolean (or a `literal(true)`) is described as `boolean`, an enum as `enum`, and an array of an enum as `multiselect`, with `options`. A boolean field that should be a `Switch` can say so with `.meta({ control: "switch" })`, which arrives in `meta`.

## Server-side validation

The browser is not a trust boundary: anyone can post any values. Validate the post on the server with the same schema. A native form post is awkward for choice controls, since an unticked checkbox sends nothing and a group sends one key several times, so `parseFormData` reads the post for you.

```ts
// app/actions.ts
"use server";
import { parseFormData } from "@azmr/ui/zod"; // or "@azmr/ui/effect" with a Schema.Struct

export async function save(formData: FormData) {
  const result = await parseFormData(schema, formData);
  if (!result.success) return { errors: result.errors };
  await store(result.data); // typed, and every choice is one your schema allows
}
```

`parseFormData` walks the schema's own fields, never the keys that were posted, so a key the schema does not declare (`isAdmin`, `__proto__`) is ignored. Because the schema checks the values, a plan or tag outside your `z.enum`, `terms=false`, or a repeated key on a single-value field fails here even though the browser would never send it. `formDataToValues(formData, fields)` is the first step on its own.

| Field type                                         | What `formDataToValues` gives the schema                                                                                                                        |
| -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `boolean`                                          | `true` for exactly one entry equal to `"on"` or `"true"`; `false` when absent. Any other string, such as `"false"`, is passed through so the schema rejects it. |
| `multiselect` (an array of an enum, or of strings) | Every string entry for the name (files dropped); `[]` when there are none, so one ticked box is still an array.                                                 |
| `enum` and the rest                                | The single string; left out when absent or a file; an array when the key was posted more than once, so a single-value schema rejects it.                        |

Write a boolean field as `z.boolean()` (or `z.literal(true)` for a must-accept box), never `z.coerce.boolean()`: that reads every non-empty string, `"false"` included, as true, so `parseFormData` throws if it finds one. The controls do not accept `uncheckedValue`, so an unticked box posts nothing. Numbers and dates reach the schema as the strings that were posted; use your schema to parse them. Top-level fields only: nested paths such as `address.city` are not read from a post.

## Props

| Prop              | Type                                                                                      | Default     | Required | Description                                                                                                                                                                                                                                                  |
| ----------------- | ----------------------------------------------------------------------------------------- | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `name`            | `string`                                                                                  | `undefined` | No       | Identifies the field when a form is submitted.                                                                                                                                                                                                               |
| `checked`         | `boolean \| undefined`                                                                    | `undefined` | No       | Whether the checkbox is currently ticked. To render an uncontrolled checkbox, use the `defaultChecked` prop instead.                                                                                                                                         |
| `defaultChecked`  | `boolean \| undefined`                                                                    | `false`     | No       | Whether the checkbox is initially ticked. To render a controlled checkbox, use the `checked` prop instead.                                                                                                                                                   |
| `disabled`        | `boolean \| undefined`                                                                    | `false`     | No       | Whether the component should ignore user interaction.                                                                                                                                                                                                        |
| `onCheckedChange` | `((checked: boolean, eventDetails: CheckboxRootChangeEventDetails) => void) \| undefined` |             | No       | Event handler called when the checkbox is ticked or unticked.                                                                                                                                                                                                |
| `readOnly`        | `boolean \| undefined`                                                                    | `false`     | No       | Whether the user should be unable to tick or untick the checkbox.                                                                                                                                                                                            |
| `required`        | `boolean \| undefined`                                                                    | `false`     | No       | Whether the user must tick the checkbox before submitting a form.                                                                                                                                                                                            |
| `indeterminate`   | `boolean \| undefined`                                                                    | `false`     | No       | Whether the checkbox is in a mixed state: neither ticked, nor unticked.                                                                                                                                                                                      |
| `parent`          | `boolean \| undefined`                                                                    | `false`     | No       | Whether the checkbox controls a group of child checkboxes. Must be used in a [Checkbox Group](https://base-ui.com/react/components/checkbox-group).                                                                                                          |
| `value`           | `string`                                                                                  |             | No       | The checkbox's value. Identifies it within a [Checkbox Group](https://base-ui.com/react/components/checkbox-group), falling back to `name` when omitted. When submitting a form, a checked box submits `value`; with no `value`, it submits the native "on". |
| `size`            | `"sm" \| "md" \| "lg" \| undefined`                                                       |             | No       | Inside a group, overrides the group's size.                                                                                                                                                                                                                  |
| `description`     | `ReactNode`                                                                               |             | No       | Help text under the label, read out after it.                                                                                                                                                                                                                |
| `error`           | `ReactNode`                                                                               |             | No       | Marks the checkbox invalid and shows the message under it. Not used inside a group.                                                                                                                                                                          |
| `className`       | `string`                                                                                  |             | No       |                                                                                                                                                                                                                                                              |

`Switch` takes the same props, minus `indeterminate`, `parent` and `value`'s group meaning. Each also needs a `label`, `aria-label` or `aria-labelledby`.

| Prop             | Type                                                            | Default | Required | Description                                                                                                                                                                                               |
| ---------------- | --------------------------------------------------------------- | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `description`    | `ReactNode`                                                     |         | No       |                                                                                                                                                                                                           |
| `error`          | `ReactNode`                                                     |         | No       | Shown under the group and read out as its description.                                                                                                                                                    |
| `required`       | `boolean \| undefined`                                          |         | No       | Shows the required marker on the legend.                                                                                                                                                                  |
| `size`           | `"sm" \| "md" \| "lg" \| undefined`                             |         | No       | Applied to every checkbox unless it sets its own.                                                                                                                                                         |
| `orientation`    | `"horizontal" \| "vertical" \| undefined`                       |         | No       |                                                                                                                                                                                                           |
| `value`          | `string[] \| undefined`                                         |         | No       |                                                                                                                                                                                                           |
| `defaultValue`   | `string[] \| undefined`                                         |         | No       |                                                                                                                                                                                                           |
| `onValueChange`  | `((value: string[]) => void) \| undefined`                      |         | No       |                                                                                                                                                                                                           |
| `name`           | `string`                                                        |         | No       | Every ticked checkbox posts its `value` under this name.                                                                                                                                                  |
| `disabled`       | `boolean \| undefined`                                          |         | No       |                                                                                                                                                                                                           |
| `allValues`      | `readonly string[] \| undefined`                                |         | No       | With hand-written children and a `parent` checkbox: every value in the group, disabled ones included. Select all leaves a disabled checkbox as it is. With `options`, `selectAllLabel` does this for you. |
| `onBlur`         | `((event: React.FocusEvent<HTMLElement>) => void) \| undefined` |         | No       | Called when focus leaves the group, not when it moves between the checkboxes inside it.                                                                                                                   |
| `selectAllLabel` | `ReactNode`                                                     |         | No       | With `options`: adds a "select all" checkbox first. It shows mixed while only some are ticked.                                                                                                            |
| `className`      | `string`                                                        |         | No       |                                                                                                                                                                                                           |
| `options`        | `readonly ChoiceOption[] \| undefined`                          |         | No       | The choices. Each is `{ value, label, description?, disabled? }` and nothing else is read.                                                                                                                |
| `children`       | `ReactNode`                                                     |         | No       | `Checkbox`es with a `value`, for layouts `options` does not cover.                                                                                                                                        |

`RadioGroup` takes the same props except `allValues` and `selectAllLabel`; its `value`, `defaultValue` and `onValueChange` use one string, and it adds `readOnly`. `Radio` takes `value`, `label`, `description`, `disabled` and `size`.

## Accessibility

- A group is named by its legend, and `error` and `description` are its accessible description. `aria-invalid` and `aria-required` are set on a radio group, which allows them; a checkbox group has role `group`, which does not, so its error is read out as its description and its required marker sits on the legend.
- Each item's `description` is its accessible description, and a required control gets `aria-required`. The red `*` is hidden from screen readers, which hear the required state instead.
- Errors appear in a polite live region, so they are announced when they arrive.
- `disabled` and `readOnly` controls ignore changes; a disabled option is skipped by the arrow keys.
- The checked state is not shown by colour alone: a ticked checkbox draws a check, an indeterminate one a bar, and a radio a dot.

| Key                         | Action                                                                                                         |
| --------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `Tab`                       | Moves to the next checkbox or switch. A radio group is one stop: it lands on the selected radio, or the first. |
| `Space`                     | Toggles the focused checkbox or switch, or selects the focused radio.                                          |
| `ArrowDown` or `ArrowRight` | In a radio group, moves to the next radio and selects it, wrapping at the end.                                 |
| `ArrowUp` or `ArrowLeft`    | In a radio group, moves to the previous radio and selects it, wrapping at the start.                           |
