# Checkbox

A control that the user checks or unchecks, with an optional partly checked state. It renders a native button with the checkbox role, and a hidden checkbox beside it so that forms submit its value.

- Entry point: `menhir/checkbox`
- Size: 1.7 kB, minified and gzipped, Solid left out

> To add Checkbox to a project, install the packages below with the project's package manager, then copy the example that matches how the project is styled, Tailwind CSS or plain CSS, and adapt its markup and class names to the project.

## Install

```sh
pnpm add menhir solid-js @solidjs/web
```

## Anatomy

```tsx
<Checkbox.Root>
  <Checkbox.Indicator />
</Checkbox.Root>
```

## Example

### Tailwind CSS

`CheckboxExample.tsx`:

```tsx
import { Checkbox } from "menhir/checkbox";
import { For, createSignal } from "solid-js";

const topics = ["Product news", "Security alerts"];

const box =
  "inline-flex size-5 cursor-pointer items-center justify-center rounded border border-stone-400 text-white focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-stone-500 data-checked:border-transparent data-checked:bg-stone-800 data-indeterminate:border-transparent data-indeterminate:bg-stone-800 dark:border-stone-500 dark:text-stone-900 dark:data-checked:bg-stone-300 dark:data-indeterminate:bg-stone-300";
// A check from two borders of a rotated box, a dash from one.
const mark =
  "hidden border-0 border-current data-checked:block data-checked:h-2.5 data-checked:w-1.5 data-checked:-translate-y-px data-checked:rotate-45 data-checked:border-r-2 data-checked:border-b-2 data-indeterminate:block data-indeterminate:w-2 data-indeterminate:border-b-2";

export default function CheckboxExample() {
  const [checked, setChecked] = createSignal([false, true]);
  const all = () => checked().every(Boolean);
  const some = () => checked().some(Boolean);
  return (
    <div class="inline-flex flex-col gap-2">
      <label class="inline-flex items-center gap-2">
        <Checkbox.Root
          checked={all()}
          indeterminate={some() && !all()}
          onCheckedChange={(value) => setChecked(topics.map(() => value))}
          class={box}
        >
          <Checkbox.Indicator class={mark} />
        </Checkbox.Root>
        Email updates
      </label>
      <For each={topics}>
        {(topic, index) => (
          <label class="ml-7 inline-flex items-center gap-2">
            <Checkbox.Root
              name="topics"
              value={topic}
              checked={checked()[index()]}
              onCheckedChange={(value) =>
                setChecked((current) =>
                  current.map((old, i) => (i === index() ? value : old)),
                )
              }
              class={box}
            >
              <Checkbox.Indicator class={mark} />
            </Checkbox.Root>
            {topic}
          </label>
        )}
      </For>
    </div>
  );
}
```

### CSS

`CheckboxExample.tsx`:

```tsx
import { Checkbox } from "menhir/checkbox";
import { For, createSignal } from "solid-js";

import "./checkbox.css";

const topics = ["Product news", "Security alerts"];

export default function CheckboxExample() {
  const [checked, setChecked] = createSignal([false, true]);
  const all = () => checked().every(Boolean);
  const some = () => checked().some(Boolean);
  return (
    <div class="checkbox-example">
      <label>
        <Checkbox.Root
          checked={all()}
          indeterminate={some() && !all()}
          onCheckedChange={(value) => setChecked(topics.map(() => value))}
          class="checkbox"
        >
          <Checkbox.Indicator class="indicator" />
        </Checkbox.Root>
        Email updates
      </label>
      <For each={topics}>
        {(topic, index) => (
          <label class="child">
            <Checkbox.Root
              name="topics"
              value={topic}
              checked={checked()[index()]}
              onCheckedChange={(value) =>
                setChecked((current) =>
                  current.map((old, i) => (i === index() ? value : old)),
                )
              }
              class="checkbox"
            >
              <Checkbox.Indicator class="indicator" />
            </Checkbox.Root>
            {topic}
          </label>
        )}
      </For>
    </div>
  );
}
```

`checkbox.css`:

```css
/* The least CSS that makes the Checkbox visible: a box, filled while
   checked or partly checked, with a check mark or a dash chosen by
   data-checked and data-indeterminate. Everything else is the browser's.
   Colours are Tailwind's stone palette; light-dark() picks the second one in
   dark mode (color-scheme: dark). */
.checkbox-example {
  display: inline-flex;
  flex-direction: column;
  gap: 0.5rem;
  font-family: system-ui, sans-serif;
}
.checkbox-example label {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
}
.checkbox-example .child {
  margin-left: 1.75rem;
}

.checkbox {
  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 1.25rem;
  height: 1.25rem;
  padding: 0;
  border: 1px solid
    light-dark(
      oklch(70.9% 0.01 56.259) /* stone-400 */,
      oklch(55.3% 0.013 58.071) /* stone-500 */
    );
  border-radius: 0.25rem;
  background: transparent;
  color: light-dark(#fff, oklch(21.6% 0.006 56.043) /* stone-900 */);
  cursor: pointer;
}
.checkbox:is([data-checked], [data-indeterminate]) {
  border-color: transparent;
  background: light-dark(
    oklch(26.8% 0.007 34.298) /* stone-800 */,
    oklch(86.9% 0.005 56.366) /* stone-300 */
  );
}

/* Marks drawn with borders, not SVG: a check from two borders of a rotated
   box, a dash from one. */
.indicator {
  display: none;
  box-sizing: border-box;
  border: 0 solid currentColor;
}
.indicator[data-checked] {
  display: block;
  width: 0.375rem;
  height: 0.625rem;
  border-width: 0 2px 2px 0;
  transform: translateY(-1px) rotate(45deg);
}
.indicator[data-indeterminate] {
  display: block;
  width: 0.5rem;
  border-bottom-width: 2px;
}
```

## API reference

### Root

The checkbox: a <button role="checkbox">, followed by a visually hidden <input type="checkbox"> for forms. Label it with a <label> around it or one whose for matches its id, or put it in a Field (In a Field, below). Its render function must render a <button>.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `checked` | `boolean` | — | Whether the checkbox is checked, when controlled. Pair it with onCheckedChange. |
| `defaultChecked` | `boolean` | `false` | Whether the checkbox starts checked, when uncontrolled. A form reset goes back to it. |
| `onCheckedChange` | `(checked: boolean) => void` | — | Called with the new value when the user checks or unchecks the checkbox, or the form is reset. A controlled checkbox changes only if checked does. |
| `indeterminate` | `boolean` | `false` | Whether the checkbox is partly checked, such as the parent of a group whose children are only some checked. Its aria-checked is "mixed". A click still asks for the opposite of checked, so a mixed checkbox that is not checked asks to be checked. |
| `disabled` | `boolean` | `false` | Whether the checkbox ignores the user. It cannot be focused, and the form does not submit it. |
| `readOnly` | `boolean` | `false` | Whether the checkbox can be focused but not checked or unchecked. |
| `required` | `boolean` | `false` | Whether the form can be submitted only while the checkbox is checked. |
| `name` | `string` | — | The name the form submits the checkbox under. |
| `value` | `string` | `"on"` | What the form submits while the checkbox is checked. |
| `form` | `string` | — | The id of the form the checkbox belongs to, when it is not inside it. |
| `render` | `(props) => JSX.Element` | — | Renders the checkbox with your own button component. Read once. |

### Indicator

The check mark: a <span>, always rendered, with the same data attributes as Root (data-checked, data-unchecked or data-indeterminate) so that your CSS shows it. Place it inside Root.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `(props) => JSX.Element` | — | Renders the indicator with your own component. |

## Keyboard

| Keys | Action |
| --- | --- |
| `Space` | Checks or unchecks the checkbox. |
| `Tab` | Moves focus to or away from the checkbox. |

## In a Field

A Checkbox joins a Field as Field.Control's render: the Field gives the button its id, label, description and error, and the hidden input its name. The value props are the Checkbox's, so a controlled Checkbox is rendered with a function that puts checked and onCheckedChange on it. A required Checkbox that is unchecked shows its error once the user has left it, unchecked it again or tried to submit the form, and when the browser blocks the submission, focus moves to the checkbox. The Field's data-invalid and data-touched are on the button; style the Indicator through it, as in [data-invalid] .indicator. A Checkbox outside a Field costs nothing more.

`CheckboxInField.tsx`:

```tsx
import { createSignal } from "solid-js";
import { Checkbox } from "menhir/checkbox";
import { Field } from "menhir/field";

export default function CheckboxInField() {
  const [accepted, setAccepted] = createSignal(false);
  return (
    <Field.Root name="terms">
      <Field.Control
        required
        render={(props) => (
          <Checkbox.Root
            {...props}
            checked={accepted()}
            onCheckedChange={setAccepted}
          />
        )}
      >
        <Checkbox.Indicator />
      </Field.Control>
      <Field.Label>Accept the terms</Field.Label>
      <Field.Description>You can read them on the next page.</Field.Description>
      <Field.Error match="valueMissing">Check this to go on.</Field.Error>
    </Field.Root>
  );
}
```
