---
title: Checkbox
description: Capture an independent checked, unchecked, or mixed choice.
package: moraine
version: 0.11.0
repository: https://github.com/subframe7536/moraine
---

# Checkbox

> Capture an independent checked, unchecked, or mixed choice.

## Anatomy

```text
Checkbox [component; slot=root]
├── container [slot]
│   ├── input [internal]
│   └── control [slot]
│       └── indicator [slot]
│           └── icon [internal]
└── wrapper [slot]
    ├── label [slot]
    └── description [slot]
```

## Usage

Use Checkbox for an independent boolean or mapped choice that can be selected alongside other
choices. Use [Switch](https://moraine.subf.dev/components/switch.md) when the control represents an immediate on/off setting.
Use [CheckboxGroup](https://moraine.subf.dev/components/checkbox-group.md) when several choices submit as one array.

```tsx
import { Checkbox } from 'moraine'

export function Example() {
  return <Checkbox label="Accept terms" />
}
```

### State and form values

Use `checked` with `onCheckedChange` for controlled state, or `defaultChecked` for an initial value.
Pass `checked="indeterminate"` from aggregate selection state; it shows the mixed presentation
without adding a third submitted value.

`trueValue` and `falseValue` map the checked state to domain values. `onCheckedChange` receives them,
and a bound `form.Field` stores them. Native form submission uses `value` while checked. Without
`value`, it submits a string or number `trueValue`, or `'on'` otherwise. An unchecked or
indeterminate checkbox contributes no entry. `onCheckedChange` fires only for user toggles, never
while `disabled` or `readOnly`, and toggling from `'indeterminate'` checks the box.

```tsx
<Checkbox
  checked={checked()}
  onCheckedChange={setChecked}
  label="Subscribe to product updates"
/>
<Checkbox trueValue="opted-in" falseValue="opted-out" label="Anonymous telemetry" />
```

### Label, description, and layout

`label` and `description` render beside the control and link to it for assistive technology. Set
`variant="card"` to draw a bordered card whose whole surface toggles the checkbox, except for
interactive content inside it. `indicatorPosition` places the control at the `leading` (default) or
`trailing` edge, or hides it visually with `hidden`. `size` accepts `sm`, `md` (default), or `lg`.

```tsx
<Checkbox
  variant="card"
  indicatorPosition="trailing"
  label="Email alerts"
  description="Get a message when a build fails."
/>
```

### Read-only and disabled

`disabled` removes the control from normal interaction and native form submission. `readOnly`
preserves the value and focusability while preventing changes.

```tsx
<Checkbox disabled defaultChecked label="Disabled" />
<Checkbox readOnly defaultChecked label="Read-only" />
```

## Examples

### Complete a deployment checklist

Drive a parent checkbox from child task state. Pass `checked="indeterminate"` when some but not all
tasks are done. `checkedIcon` and `indeterminateIcon` replace the default marks.

```tsx
import { Checkbox } from 'moraine'
import { createMemo, createSignal, For } from 'solid-js'

export function IndeterminateCustomIcons() {
  const [tasks, setTasks] = createSignal([
    { id: 'tests', label: 'Run unit and integration test suites', checked: true },
    { id: 'build', label: 'Build static assets and server bundle', checked: true },
    { id: 'migrate', label: 'Apply pending database migrations', checked: false },
  ])

  const checkedCount = createMemo(() => tasks().filter((t) => t.checked).length)
  const allChecked = createMemo(() => checkedCount() === tasks().length)
  const isIndeterminate = createMemo(() => checkedCount() > 0 && checkedCount() < tasks().length)

  const parentState = createMemo<'indeterminate' | boolean>(() => {
    if (isIndeterminate()) {
      return 'indeterminate'
    }
    return allChecked()
  })

  const toggleAll = () => {
    const nextState = !allChecked()
    setTasks((current) => current.map((task) => ({ ...task, checked: nextState })))
  }

  const toggleTask = (id: string) => {
    setTasks((current) =>
      current.map((task) => (task.id === id ? { ...task, checked: !task.checked } : task)),
    )
  }

  return (
    <div class="p-4 b-1 b-border rounded-xl max-w-xl space-y-4">
      <Checkbox
        label="Production deployment checklist"
        description={`${checkedCount()} of ${tasks().length} tasks completed`}
        checked={parentState()}
        onCheckedChange={toggleAll}
        checkedIcon="i-lucide:check-check"
        indeterminateIcon="i-lucide:minus"
      />

      <div class="pl-6 border-border border-l-2 space-y-2">
        <For each={tasks()}>
          {(task) => (
            <Checkbox
              size="sm"
              label={task.label}
              checked={task.checked}
              onCheckedChange={() => toggleTask(task.id)}
            />
          )}
        </For>
      </div>
    </div>
  )
}
```

### Store telemetry as domain values

Map checked and unchecked to application strings with `trueValue` and `falseValue`. Callbacks and
schema fields then receive those strings instead of booleans.

```tsx
import { Badge, Checkbox } from 'moraine'
import { createSignal } from 'solid-js'

export function CustomTrueFalseValues() {
  const [telemetry, setTelemetry] = createSignal<'opted-in' | 'opted-out'>('opted-in')

  return (
    <div class="p-4 b-1 b-border rounded-xl max-w-xl space-y-4">
      <div class="flex gap-4 items-center justify-between">
        <Checkbox<'opted-in', 'opted-out'>
          label="Anonymous telemetry collection"
          description="Send anonymous crash diagnostics and performance reports."
          trueValue="opted-in"
          falseValue="opted-out"
          checked={telemetry()}
          onCheckedChange={setTelemetry}
        />
        <Badge variant={telemetry() === 'opted-in' ? 'soft' : 'outline'}>{telemetry()}</Badge>
      </div>

      <p class="text-xs text-muted-foreground">
        Controlled domain state is stored as <code class="font-mono">{telemetry()}</code> instead of
        a raw boolean.
      </p>
    </div>
  )
}
```

### Save cookie consent for Consent Mode

Consent Mode reads each consent type as `'granted'` or `'denied'`. Set `trueValue="granted"` and
`falseValue="denied"` inside `form.Field`. The schema validates and submits those strings directly,
so the output goes straight to `gtag('consent', 'update', ...)` without a boolean mapping step.

```tsx
import { Button, Checkbox, createForm } from 'moraine'
import { Show, createSignal } from 'solid-js'
import * as v from 'valibot'

// Consent Mode expects 'granted' | 'denied' rather than booleans.
const ConsentState = v.picklist(['granted', 'denied'])

const consentSchema = v.object({
  analytics_storage: ConsentState,
  ad_storage: ConsentState,
  ad_personalization: ConsentState,
})

type ConsentUpdate = v.InferOutput<typeof consentSchema>

export function ConsentPreferences() {
  const [saved, setSaved] = createSignal<ConsentUpdate>()
  const form = createForm({
    schema: consentSchema,
    // Privacy-first default: nothing optional is granted until the visitor opts in.
    initialInput: {
      analytics_storage: 'denied',
      ad_storage: 'denied',
      ad_personalization: 'denied',
    },
  })

  return (
    <form.Form onSubmit={(output) => setSaved(output)}>
      <div class="p-4 b-1 b-border rounded-xl max-w-xl space-y-4">
        <div class="space-y-3">
          <form.Field name="analytics_storage">
            <Checkbox
              trueValue="granted"
              falseValue="denied"
              label="Analytics"
              description="Measure page views and feature usage to improve the product."
            />
          </form.Field>
          <form.Field name="ad_storage">
            <Checkbox
              trueValue="granted"
              falseValue="denied"
              label="Advertising"
              description="Store cookies that measure ad performance."
            />
          </form.Field>
          <form.Field name="ad_personalization">
            <Checkbox
              trueValue="granted"
              falseValue="denied"
              label="Personalized ads"
              description="Use activity on this site to tailor ads elsewhere."
            />
          </form.Field>
        </div>

        <Button type="submit" size="sm">
          Save preferences
        </Button>

        <pre class="text-xs font-mono p-3 rounded-md bg-muted overflow-x-auto">
          <Show when={saved()} fallback="Save to see the consent update payload.">
            {(update) => `gtag('consent', 'update', ${JSON.stringify(update(), null, 2)})`}
          </Show>
        </pre>
      </div>
    </form.Form>
  )
}
```

### Require terms on submit

Bind the checkbox to `form.Field` and reject `false` in the schema so submit cannot proceed until
the terms are accepted.

```tsx
import { Button, Checkbox, createForm } from 'moraine'
import { createSignal } from 'solid-js'
import * as v from 'valibot'

export function FormIntegration() {
  const [submitted, setSubmitted] = createSignal<boolean | null>(null)
  const form = createForm({
    schema: v.object({
      terms: v.pipe(v.boolean(), v.literal(true, 'You must accept the terms to proceed.')),
    }),
    initialInput: { terms: false },
    validate: 'input',
  })

  return (
    <form.Form onSubmit={(output) => setSubmitted(output.terms)}>
      <div class="max-w-xl space-y-4">
        <form.Field name="terms" description="Required for account activation." required>
          <Checkbox label="I agree to the Terms of Service and Privacy Policy" />
        </form.Field>
        <div class="flex gap-3 items-center">
          <Button type="submit" variant="soft" tone="neutral" size="sm">
            Validate
          </Button>
          <p class="text-xs text-muted-foreground">
            Terms accepted: {submitted() === null ? 'Pending' : submitted() ? 'Yes' : 'No'}
          </p>
        </div>
      </div>
    </form.Form>
  )
}
```

### Subscribe to product updates

Own `checked` in the page when nearby copy must reflect the same boolean.

```tsx
import { Checkbox } from 'moraine'
import { createSignal } from 'solid-js'

export function StateAndValues() {
  const [checked, setChecked] = createSignal(true)

  return (
    <div class="flex flex-col gap-3">
      <Checkbox
        checked={checked()}
        onCheckedChange={setChecked}
        label="Subscribe to product updates"
        description="Receive weekly summaries of new releases and features."
      />
      <p class="text-xs text-muted-foreground">
        Current state:{' '}
        <span class="text-foreground font-medium">{checked() ? 'checked' : 'unchecked'}</span>
      </p>
    </div>
  )
}
```

### Lock a policy versus show a read-only copy

`disabled` removes the control from interaction and native submit. `readOnly` stays focusable and
submits, but rejects changes.

```tsx
import { Checkbox } from 'moraine'

export function DisabledReadonly() {
  return (
    <div class="flex flex-col gap-4">
      <Checkbox
        disabled
        defaultChecked
        label="Disabled (checked)"
        description="Non-interactive and removed from form submission."
      />
      <Checkbox
        readOnly
        defaultChecked
        label="Read-only (checked)"
        description="Focusable and submitted, but prevents value changes."
      />
    </div>
  )
}
```

## API Reference

### Attributes

| Attributes | Slot | Description |
| --- | --- | --- |
| `data-checked` | `checkbox`, `checkbox-control`, `checkbox-indicator` | Present when the item or toggle is checked. |
| `data-disabled` | `checkbox`, `checkbox-control`, `checkbox-indicator` | Present when the component, slot, or item is disabled. |
| `data-indeterminate` | `checkbox`, `checkbox-control`, `checkbox-indicator` | Present when the checkbox or progress state is indeterminate. |
| `data-invalid` | `checkbox`, `checkbox-control` | Present when the field or form has a validation error. |
| `data-readonly` | `checkbox`, `checkbox-control` | Present when the field is in read-only mode. |
| `data-required` | `checkbox`, `checkbox-control`, `checkbox-label` | Present when the field input is required. |
| `data-unchecked` | `checkbox`, `checkbox-control` | Present when the checkbox, radio item, or switch is unchecked. |

### Props

Props for the Checkbox component.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| checked | TTrue \| TFalse \| 'indeterminate' \| undefined | — | Whether the checkbox is checked (controlled). Accepts `trueValue` or `true` for checked,<br>`falseValue` or `false` for unchecked, and `'indeterminate'` for the mixed state. Leave it<br>`undefined` for uncontrolled state; update it from `onCheckedChange`. |
| checkedIcon | IconT.Name \| undefined | 'icon-check' | Icon to show when checked. |
| defaultChecked | boolean \| 'indeterminate' \| undefined | false | Initial checked state when uncontrolled; also the state restored when the surrounding<br>native form is reset. Accepts `true`, `false`, or `'indeterminate'`. |
| description | JSX.Element \| undefined | — | Description rendered under the label and linked to the control with `aria-describedby`. |
| disabled | boolean \| undefined | false | Whether the control is disabled: it cannot be interacted with and sets `aria-disabled`.<br>When omitted, the control inherits `disabled` from the surrounding `Field`; an explicit<br>`false` overrides the `Field`. |
| falseValue | TFalse \| undefined | false | Value that represents the unchecked state, passed to `onCheckedChange` and stored as the<br>value of a bound `Field`. |
| form | string \| undefined | — | The id of a `<form>` the hidden input belongs to, instead of the closest<br>ancestor form. |
| id | string \| undefined | — | The ID of the control's main focusable element, which a surrounding `Field` label points to<br>with `for`. A unique ID is generated when omitted. The control's related parts (hidden<br>input, label, description) derive their IDs from it, so keep it unique on the page. |
| indeterminateIcon | IconT.Name \| undefined | 'icon-minus' | Icon to show when indeterminate. |
| indicatorPosition | 'leading' \| 'trailing' \| 'hidden' \| undefined | 'leading' | Placement of the selection indicator relative to the label. |
| inputRef | Ref<HTMLInputElement> \| undefined | — | Ref to the hidden native `<input type="checkbox">` that carries the form value. The visible<br>control is a separate `<button role="checkbox">`. |
| label | JSX.Element \| undefined | — | Label rendered beside the control and linked to it. With `variant="card"` the whole card<br>toggles the checkbox when clicked. |
| name | string \| undefined | — | The name of the control, used for native form submission. When omitted, the control uses<br>the name of its form binding or a string `name` set on the surrounding `Field`. |
| onCheckedChange | ((value: TTrue \| TFalse) => void) \| undefined | — | Called when the user toggles the checkbox, with `trueValue` (now checked) or `falseValue`<br>(now unchecked). Toggling from `'indeterminate'` checks it. Not called while `disabled` or<br>`readOnly`, nor when `checked` changes from outside. |
| onPointerDown | JSX.EventHandlerUnion<HTMLButtonElement, PointerEvent> \| undefined | — | Handler for `pointerdown` on the checkbox control button. Call `event.preventDefault()` to<br>skip the built-in handling, which keeps focus on the hidden input when it is already<br>focused. |
| readOnly | boolean \| undefined | false | Whether the control is read-only: the value is visible and focusable but cannot be changed,<br>and `aria-readonly` is set. When omitted, the control inherits `readOnly` from the<br>surrounding `Field`. |
| required | boolean \| undefined | false | Whether the control is required, which sets `aria-required` (and the native `required`<br>attribute where the control renders a native input). When omitted, the control inherits<br>`required` from the surrounding `Field`. |
| size | 'sm' \| 'md' \| 'lg' \| undefined | 'md' | Visual size of the component. |
| trueValue | TTrue \| undefined | true | Value that represents the checked state: it is passed to `onCheckedChange`, stored as the<br>value of a bound `Field`, and compared with `checked`. A string or number `trueValue` is<br>also the native value submitted when `value` is not set. |
| value | string \| undefined | — | Native value submitted when the checkbox is checked. Defaults to a string or number<br>`trueValue`, otherwise `'on'`. |
| variant | 'card' \| 'list' \| undefined | — | Visual treatment of the component. |
| class | SlotClassValue \| undefined | — | Class applied to the component root or trigger element. |
| classes | Classes \| undefined | — | Family slot class defaults for this instance. |
| style | SlotStyleValue \| undefined | — | Style applied to the component root or trigger element. |
| styles | Styles \| undefined | — | Family slot style defaults for this instance. |

**`trueValue` example**

```tsx
import { Checkbox } from 'moraine'

<Checkbox
  trueValue="yes"
  falseValue="no"
  label="Accept the terms"
  onCheckedChange={(value) => console.log(value)} // 'yes' or 'no'
/>
```
