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 forms#

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. onCheckedChange fires only for user toggles, never while disabled or readOnly, and toggling from 'indeterminate' checks the box.

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, or falls back to a string or number trueValue (or 'on' otherwise). An unchecked or indeterminate checkbox contributes no entry.

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

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#

Indeterminate and custom icons#

Pass checked="indeterminate" for partial selection states, and override the default marks with checkedIcon and indeterminateIcon.

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

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

Custom values in form#

Combine trueValue and falseValue with form.Field so schema validation and form submission use custom string values directly without boolean mapping.

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

Form#

Bind Checkbox to form.Field to validate required acceptance through the form schema.

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

Controlled#

Control checked with onCheckedChange to sync state with surrounding UI.

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

Disabled and read-only#

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