# Checkbox

A box to turn one option on or off, or a group of boxes for several options.

- Family: selection
- Import: `import { Checkbox, CheckboxGroup } from "@senvenli/react/selection";`
- Page: https://design.senvenli.com/docs/components/checkbox
- JSON: https://design.senvenli.com/docs/components/checkbox.json

## Example: One option

A single box, written positively, with a line of detail.

```tsx
import { Checkbox } from "@senvenli/react/selection";

export default function Example() {
  return (
    <Checkbox defaultSelected description="One email a month, no more.">
      Send me product updates
    </Checkbox>
  );
}
```

## Examples

### A group

Several options under one legend.

```tsx
import { Checkbox, CheckboxGroup } from "@senvenli/react/selection";

export default function Example() {
  return (
    <CheckboxGroup label="Notify me about" description="Sent to ada@example.com." defaultValue={["orders", "invoices"]}>
      <Checkbox value="orders">New orders</Checkbox>
      <Checkbox value="invoices">Paid invoices</Checkbox>
      <Checkbox value="comments">Comments on my projects</Checkbox>
    </CheckboxGroup>
  );
}
```

### Indeterminate parent

A parent box shows a minus while only some of its options are checked.

```tsx
import { Stack } from "@senvenli/react/layout";
import { Checkbox, CheckboxGroup } from "@senvenli/react/selection";
import { useState } from "react";

const COLUMNS = [
  { value: "customer", label: "Customer" },
  { value: "status", label: "Status" },
  { value: "total", label: "Total" },
];

export default function Example() {
  const [shown, setShown] = useState(["customer", "total"]);
  const all = shown.length === COLUMNS.length;
  return (
    <Stack space="space-150">
      <Checkbox
        isSelected={all}
        isIndeterminate={shown.length > 0 && !all}
        onChange={(isSelected) => setShown(isSelected ? COLUMNS.map((column) => column.value) : [])}
      >
        Show all columns
      </Checkbox>
      <CheckboxGroup label="Columns" value={shown} onChange={setShown}>
        {COLUMNS.map((column) => (
          <Checkbox key={column.value} value={column.value}>
            {column.label}
          </Checkbox>
        ))}
      </CheckboxGroup>
    </Stack>
  );
}
```

### Invalid and disabled

The error sits under the label; disabled options keep their value.

```tsx
import { Stack } from "@senvenli/react/layout";
import { Checkbox } from "@senvenli/react/selection";

export default function Example() {
  return (
    <Stack space="space-150">
      <Checkbox isInvalid errorMessage="Accept the terms to continue.">
        I accept the terms of service
      </Checkbox>
      <Checkbox isDisabled>Share usage data</Checkbox>
      <Checkbox isDisabled defaultSelected description="Required by your workspace.">
        Two-step sign-in
      </Checkbox>
    </Stack>
  );
}
```

### Sizes

`size` small, medium (default) or large; a CheckboxGroup sets it for its boxes.

```tsx
import { Checkbox } from "@senvenli/react/selection";
import { Stack } from "@senvenli/react/layout";

export default function Example() {
  return (
    <Stack space="space-150">
      <Checkbox size="small" defaultSelected>
        Small
      </Checkbox>
      <Checkbox defaultSelected>Medium</Checkbox>
      <Checkbox size="large" defaultSelected>
        Large
      </Checkbox>
    </Stack>
  );
}
```

## Guidelines

### When to use it

- Agreeing to something, or choosing several options from a few.

### Use something else when

- [switch](https://design.senvenli.com/docs/components/switch.md): The setting applies at once.

### Do and avoid

- Write the option positively: "Send notifications", not "Don't send…".

## Accessibility

Keyboard:

- Space: Toggles the box.

Built in:

- Required fields show "Fill in this field." after a blur or a submit; your own `errorMessage` replaces it.

You provide:

- A label for each box and a legend for the group.

## API reference

### Checkbox

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| size | `ComponentSize` |  | no | `small`, `medium` (default) or `large`; a group's size, then the provider default, otherwise. |
| children | `React.ReactNode` |  | yes | The option, written positively ("Send notifications"). |
| isSelected | `boolean` |  | no |  |
| defaultSelected | `boolean` |  | no |  |
| isIndeterminate | `boolean` |  | no | A parent of a partially selected list; shows a minus, never a check. |
| onChange | `(isSelected: boolean) => void` |  | no |  |
| description | `React.ReactNode` |  | no |  |
| isInvalid | `boolean` |  | no |  |
| errorMessage | `React.ReactNode` |  | no | Shown under the label while the checkbox is invalid (`isInvalid` or failed native validation). |
| isDisabled | `boolean` |  | no |  |
| isRequired | `boolean` |  | no | The box must be checked (terms to accept); inside a CheckboxGroup the group's `isRequired` applies instead. |
| requiredValidation | `RequiredValidation` |  | no | Who says a required box left unchecked is missing: `field` (default) shows "Fill in this field." on blur and on a DS Form submit, which it then blocks; `app` only marks it. See {@link RequiredValidation}. The app's `isInvalid` (`true` with its `errorMessage`, or `false`) overrides the check, as on TextField. Disabled, empty and required, it still blocks a DS Form's submit and cannot take focus (as TextField). |
| validationBehavior | `"aria" \| "native"` |  | no | `aria` or `native`; unset, it follows the surrounding form, else React Aria's default (`native`). |
| value | `string` |  | no | The value inside a CheckboxGroup. |
| name | `string` |  | no |  |

### CheckboxGroup

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| size | `ComponentSize` |  | no | The size of every Checkbox in the group. |
| label | `React.ReactNode` |  | yes | The visible legend, required. |
| description | `React.ReactNode` |  | no |  |
| errorMessage | `React.ReactNode` |  | no |  |
| orientation | `"horizontal" \| "vertical"` | `"vertical"` | no |  |
| children | `React.ReactNode` |  | yes |  |
| requiredValidation | `RequiredValidation` |  | no | Who says a required group with nothing checked is missing: `field` (default) shows "Fill in this field." when focus leaves the group and on a DS Form submit, which it then blocks; `app` only marks the group. See {@link RequiredValidation}. The app's `isInvalid` (`true` with its `errorMessage`, or `false`) overrides the check, as on TextField. Disabled, empty and required, it still blocks a DS Form's submit and cannot take focus (as TextField). |

Behavior props from React Aria:

| Prop | Type | Default | Required | Description |
| --- | --- | --- | --- | --- |
| defaultValue | `string[]` |  | no | The default value (uncontrolled). |
| onFocus | `(e: FocusEvent<Element, Element>) => void` |  | no | Handler that is called when the element receives focus. |
| onBlur | `(e: FocusEvent<Element, Element>) => void` |  | no | Handler that is called when the element loses focus. |
| onChange | `(value: string[]) => void` |  | no | Handler that is called when the value changes. |
| isDisabled | `boolean` |  | no | Whether the input is disabled. |
| onFocusChange | `(isFocused: boolean) => void` |  | no | Handler that is called when the element's focus status changes. |
| form | `string` |  | no | The `<form>` element to associate the input with. The value of this attribute must be the id of a `<form>` in the same document. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/input#form). |
| name | `string` |  | no | The name of the input element, used when submitting an HTML form. See [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefname). |
| value | `string[]` |  | no | The current value (controlled). |
| isRequired | `boolean` |  | no | Whether user input is required on the input before form submission. |
| isReadOnly | `boolean` |  | no | Whether the input can be selected but not changed by the user. |
| isInvalid | `boolean` |  | no | Whether the input value is invalid. |
| validate | `(value: string[]) => true \| ValidationError \| null \| undefined` |  | no | A function that returns an error message if a given value is invalid. Validation errors are displayed to the user when the form is submitted if `validationBehavior="native"`. For realtime validation, use the `isInvalid` prop instead. |
| validationBehavior | `"aria" \| "native"` |  | no | Whether to use native HTML form validation to prevent form submission when the value is missing or invalid, or mark the field as required or invalid via ARIA. |

Also takes 78 standard DOM and ARIA attributes (id, aria-label, event handlers…).

### Tokens it reads

`--ds-background-brand-bold`, `--ds-background-disabled`, `--ds-background-input`, `--ds-background-neutral-pressed`, `--ds-background-selected`, `--ds-border`, `--ds-border-bold`, `--ds-border-danger`, `--ds-border-focused`, `--ds-border-selected`, `--ds-easing-standard`, `--ds-radius-full`, `--ds-radius-large`, `--ds-radius-xsmall`, `--ds-shadow-raised`, `--ds-space-050`, `--ds-space-075`, `--ds-space-100`, `--ds-space-150`, `--ds-space-200`, `--ds-space-300`, `--ds-surface-raised`, `--ds-text`, `--ds-text-disabled`, `--ds-text-on-brand`, `--ds-text-subtlest`

## Related

- [switch](https://design.senvenli.com/docs/components/switch.md)
- [radio](https://design.senvenli.com/docs/components/radio.md)
