Skip to main content

Checkbox

Capture an independent checked, unchecked, or mixed choice.

I agree to the privacy policy and terms of service.

Props
Slots

Anatomy#

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 when the control represents an immediate on/off setting. Use CheckboxGroup when several choices submit as one array.

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.

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

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

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

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.

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>
  )
}

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.

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.

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.

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.

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
data-checked
Slot: checkboxcheckbox-controlcheckbox-indicator
Description: Present when the item or toggle is checked.
data-disabled
Slot: checkboxcheckbox-controlcheckbox-indicator
Description: Present when the component, slot, or item is disabled.
data-indeterminate
Slot: checkboxcheckbox-controlcheckbox-indicator
Description: Present when the checkbox or progress state is indeterminate.
data-invalid
Slot: checkboxcheckbox-control
Description: Present when the field or form has a validation error.
data-readonly
Slot: checkboxcheckbox-control
Description: Present when the field is in read-only mode.
data-required
Slot: checkboxcheckbox-controlcheckbox-label
Description: Present when the field input is required.
data-unchecked
Slot: checkboxcheckbox-control
Description: Present when the checkbox, radio item, or switch is unchecked.

Props#

Props for the Checkbox component. Renders a <div> element by default.

Prop