Components

Checkbox

A yes or no that is part of a form: a 16px box in a #666666 hairline on Black that fills White with a Black check, a bar for a group partly on, and a DM Sans label beside it. Form-associated.

Install

React apps get the React files; every other stack gets the web component.

npx spyglass-ds add checkbox
<script type="module" src="/spyglass-ds/elements/checkbox.js"></script>
States
A filter group
Format

Usage

Filters a person combines, consent in a form, picking rows. A setting that takes effect at once is a switch.

Never

  • A spectrum color for the checked box
  • A checkbox that acts at once without a form or an apply step
  • Faded labels for disabled: they go to the faint neutral

Props

The web component takes the same as attributes or properties (<spyglass-checkbox>); title is heading there.

<Checkbox>

PropTypeDefault
labelstring

The label, when children do not give it.

hintstring

A muted line under the label.

indeterminateboolean

A bar in place of the check, for a group partly on.

disabledboolean
invalidboolean

A red hairline.

idstring
namestring
valuestring
checkedboolean
defaultCheckedbooleanfalse
onCheckedChange(checked: boolean) => void
classNamestring
childrenReactNode

Examples

The same example in React and as web components; both render identically.

react/examples/checkbox/States.tsx
import { Checkbox } from '@/react/components/ui/Checkbox'
// Off, on, with a hint, invalid until it is checked, and disabled.

export default function States() {
  return (
    <div className="flex flex-col gap-1">
      <Checkbox label="Email me when a saved search finds new creatives" />
      <Checkbox label="Show ads that are still running" defaultChecked />
      <Checkbox label="Include UGC" hint="Creator videos posted by the brand." defaultChecked />
      <Checkbox label="I agree to the terms" invalid />
      <Checkbox label="Audio ads" hint="Coming soon." disabled />
    </div>
  )
}
elements/examples/checkbox/States.html
<!-- Off, on, with a hint, invalid until it is checked, and disabled. -->
<div class="flex flex-col gap-1">
  <spyglass-checkbox label="Email me when a saved search finds new creatives"></spyglass-checkbox>
  <spyglass-checkbox label="Show ads that are still running" checked></spyglass-checkbox>
  <spyglass-checkbox label="Include UGC" hint="Creator videos posted by the brand." checked></spyglass-checkbox>
  <spyglass-checkbox label="I agree to the terms" invalid></spyglass-checkbox>
  <spyglass-checkbox label="Audio ads" hint="Coming soon." disabled></spyglass-checkbox>
</div>
react/examples/checkbox/Group.tsx
'use client'
import { useState } from 'react'
import { Checkbox } from '@/react/components/ui/Checkbox'
// A filter group: the parent is on when every format is, a bar when some are, and turns them all on or off.
const formats = ['Video', 'Carousel', 'Static image']

export default function Group() {
  const [picked, setPicked] = useState<string[]>(['Video'])
  const all = picked.length === formats.length
  return (
    <fieldset className="flex flex-col">
      <legend className="mb-2 type-label text-fg-muted">Format</legend>
      <Checkbox label="All formats" checked={all} indeterminate={!all && picked.length > 0} onCheckedChange={(on) => setPicked(on ? formats : [])} />
      <div className="flex flex-col pl-7">
        {formats.map((f) => (
          <Checkbox key={f} label={f} checked={picked.includes(f)} onCheckedChange={(on) => setPicked(on ? [...picked, f] : picked.filter((p) => p !== f))} />
        ))}
      </div>
    </fieldset>
  )
}
elements/examples/checkbox/Group.html
<!-- A filter group: the parent is on when every format is, a bar when some are, and turns them all on or off. -->
<fieldset id="format-group" class="flex flex-col">
  <legend class="mb-2 type-label text-fg-muted">Format</legend>
  <spyglass-checkbox data-all label="All formats" indeterminate></spyglass-checkbox>
  <div class="flex flex-col pl-7">
    <spyglass-checkbox data-format label="Video" checked></spyglass-checkbox>
    <spyglass-checkbox data-format label="Carousel"></spyglass-checkbox>
    <spyglass-checkbox data-format label="Static image"></spyglass-checkbox>
  </div>
</fieldset>
<script type="module">
  const group = document.getElementById('format-group')
  const all = group.querySelector('[data-all]')
  const formats = [...group.querySelectorAll('[data-format]')]
  const sync = () => {
    const on = formats.filter((f) => f.checked).length
    all.checked = on === formats.length
    all.indeterminate = on > 0 && on < formats.length
  }
  all.addEventListener('checked-change', (e) => {
    for (const f of formats) f.checked = e.detail.value
    sync()
  })
  for (const f of formats) f.addEventListener('checked-change', sync)
</script>

Source

react/components/ui/Checkbox.tsx
'use client'
import { useEffect, useId, useRef, type ReactNode } from 'react'
import { useControllable } from '@/react/hooks/useControllable'

// shadcn's checkbox in the brand: a yes or no that is part of a form. A 16px box with a 4px corner in a #363636
// hairline on Black that lifts to #4D4D4D under the pointer; checked, it fills White and a Black check draws its stroke
// (320ms on the strong ease-out); `indeterminate` shows a bar for a group partly on. Focus is the White ring. The label
// sits right of it in DM Sans 14px, the whole row pressable, 32px tall (44px on phones); `hint` is a muted line under
// it. `invalid` turns the hairline red. A setting that takes effect at once is a switch. `checked` with
// `onCheckedChange` (or `defaultChecked` alone); the label goes in `label` or `children`.
export interface CheckboxProps {
  /** The label, when children do not give it. */
  label?: string
  /** A muted line under the label. */
  hint?: string
  /** A bar in place of the check, for a group partly on. */
  indeterminate?: boolean
  disabled?: boolean
  /** A red hairline. */
  invalid?: boolean
  id?: string
  name?: string
  value?: string
  checked?: boolean
  defaultChecked?: boolean
  onCheckedChange?: (checked: boolean) => void
  className?: string
  children?: ReactNode
}

export function Checkbox({ label, hint, indeterminate, disabled, invalid, id: given, name, value, checked, defaultChecked = false, onCheckedChange, className, children }: CheckboxProps) {
  const [on, setOn] = useControllable(checked, defaultChecked, onCheckedChange)
  const auto = useId()
  const id = given ?? `checkbox-${auto}`
  const input = useRef<HTMLInputElement | null>(null)
  // `indeterminate` is the input's property; React has no attribute for it.
  useEffect(() => {
    if (input.current) input.current.indeterminate = !!indeterminate
  }, [indeterminate])
  return (
    <>
      <style href="ds-checkbox" precedence="ds">{css}</style>
      <label data-ds="checkbox" className={className ? `ds-checkrow ${className}` : 'ds-checkrow'} htmlFor={id} data-disabled={disabled || undefined}>
        <span className="ds-checkbox">
          <input ref={input} id={id} type="checkbox" checked={on} onChange={e => setOn(e.target.checked)} name={name} value={value} disabled={disabled} aria-invalid={invalid || undefined} aria-describedby={hint ? `${id}-hint` : undefined} />
          {indeterminate
            ? <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4 8h8" /></svg>
            : <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M3.5 8.5 6.5 11.5 12.5 4.5" pathLength="1" /></svg>}
        </span>
        {(label || children || hint) && (
          <span className="flex min-w-0 flex-col">
            <span>{children ?? label}</span>
            {hint && <span id={`${id}-hint`} className="type-caption text-fg-muted">{hint}</span>}
          </span>
        )}
      </label>
    </>
  )
}

export default Checkbox

const css = `
/* The row: the box and its label, 32px tall (44px on phones), the whole row pressable. */
.ds-checkrow { display: inline-flex; min-height: var(--ds-size-control-sm); align-items: flex-start; gap: var(--ds-space-md); padding-block: 6px; color: var(--ds-color-fg); font-family: var(--ds-font-text); font-size: var(--ds-text-ui); line-height: var(--ds-text-ui-leading); cursor: pointer; }
.ds-checkrow[data-disabled] { color: var(--ds-color-fg-faint); cursor: not-allowed; }
.ds-checkbox { position: relative; display: inline-grid; width: 16px; height: 16px; flex-shrink: 0; margin-top: 2px; }
.ds-checkbox > * { grid-area: 1 / 1; }
.ds-checkbox > input { width: 16px; height: 16px; margin: 0; border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-sm); background: var(--ds-color-surface); appearance: none; cursor: inherit; transition: border-color var(--ds-duration-micro) var(--ds-easing-standard), background-color var(--ds-duration-micro) var(--ds-easing-standard); }
.ds-checkbox > input:is(:checked, :indeterminate) { border-color: var(--ds-color-action-primary); background: var(--ds-color-action-primary); }
.ds-checkbox > input:focus-visible { outline: var(--ds-border-focus) solid var(--ds-color-edge-focus); outline-offset: var(--ds-border-focus); }
.ds-checkbox > input[aria-invalid="true"]:not(:checked) { border-color: var(--ds-color-action-danger); }
.ds-checkbox > input:disabled { border-color: var(--ds-color-edge); background: var(--ds-color-action-disabled); }
.ds-checkbox > input:disabled:is(:checked, :indeterminate) { border-color: var(--ds-color-edge-strong); background: var(--ds-color-edge-strong); }
.ds-checkbox > svg { width: 16px; height: 16px; fill: none; stroke: var(--ds-color-action-primary-fg); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
.ds-checkbox > svg path[pathLength] { stroke-dasharray: 1; stroke-dashoffset: 1; transition: stroke-dashoffset var(--ds-duration-micro) var(--ds-easing-standard); }
.ds-checkbox > input:checked + svg path[pathLength] { stroke-dashoffset: 0; transition: stroke-dashoffset var(--ds-duration-glide) var(--ds-easing-out); }
.ds-checkbox > input:not(:indeterminate) + svg path:not([pathLength]) { opacity: 0; }
@media (hover: hover) and (pointer: fine) { .ds-checkrow:hover > .ds-checkbox > input:not(:disabled, :checked, :indeterminate) { border-color: var(--ds-color-action-secondary-edge-hover); } }
@media (pointer: coarse), (max-width: 767px) { .ds-checkrow { min-height: var(--ds-size-control-touch); align-items: center; padding-block: 8px; font-size: var(--ds-text-body); } .ds-checkbox { margin-top: 0; } }
@media (prefers-reduced-motion: reduce) { .ds-checkbox > svg path[pathLength], .ds-checkbox > input:checked + svg path[pathLength] { transition: none; } }
`
react/hooks/useControllable.ts
'use client'
import { useCallback, useRef, useState } from 'react'

// Vue's defineModel in React: a value that is controlled when the caller passes it (value + onValueChange, as Radix
// does) and kept inside otherwise (defaultValue). setValue calls onChange either way.
export function useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (value: T) => void) {
	const [inner, setInner] = useState<T>(defaultValue)
	const controlled = value !== undefined
	const current = controlled ? value : inner
	const ref = useRef(onChange)
	ref.current = onChange
	const set = useCallback((next: T) => {
		if (!controlled) setInner(next)
		ref.current?.(next)
	}, [controlled])
	return [current, set] as const
}
elements/components/ui/checkbox.ts
import { html, LitElement, nothing, type PropertyValues } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { live } from 'lit/directives/live.js'
import { DsFormElement, define, uid } from '@/elements/lib/element'
import styles from 'virtual:tw'

// Checkbox.tsx as <spyglass-checkbox>: a yes or no that is part of a form. A 16px box with a 4px corner in a #363636
// hairline on Black that lifts to #4D4D4D under the pointer; checked, it fills White and a Black check draws its
// stroke; `indeterminate` shows a bar for a group partly on. Focus is the White ring. The label sits right of it in
// DM Sans 14px, the whole row pressable, 32px tall (44px on phones). The host is the row (React's root label), so a
// class on the element lands on it. `checked` (the attribute is the starting state, as a native checkbox's) with the
// native `input` and `change` events and `checked-change`. Form-associated: its `name` goes with the form as `value`
// (or "on") while checked.

/**
 * @summary A yes or no that is part of a form.
 * @slot - The label (or set `label`).
 * @fires input - It was turned (read `checked`).
 * @fires change - It was turned (read `checked`).
 * @fires checked-change - It was turned; detail.value is the new state.
 */
export class Checkbox extends DsFormElement {
	static styles = [DsFormElement.styles, styles]
	static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }
	static dsField = true
	static properties = {
		checked: { type: Boolean },
		label: {},
		hint: {},
		indeterminate: { type: Boolean },
		disabled: { type: Boolean, reflect: true },
		invalid: { type: Boolean, reflect: true },
		required: { type: Boolean },
		name: {},
		value: {},
	}

	checked = false
	label?: string
	/** A muted line under the label. */
	hint?: string
	/** A bar in place of the check, for a group partly on. */
	indeterminate = false
	disabled = false
	invalid = false
	/** It must be checked for its form to send. */
	required = false
	name?: string
	/** What the form gets while it is checked ("on" when unset). */
	value?: string
	private inputId = uid('checkbox')

	constructor() {
		super()
		// The whole row is pressable, its padding too (React's root is the <label>).
		this.addEventListener('click', (event) => {
			if (event.composedPath()[0] === this) this.renderRoot.querySelector('input')?.click()
		})
	}

	protected updated(changed: PropertyValues) {
		super.updated(changed)
		if (changed.has('checked') || changed.has('value')) this.internals.setFormValue(this.checked ? (this.value ?? 'on') : null)
	}
	protected validityControl() {
		return this.renderRoot.querySelector<HTMLInputElement>('input')
	}
	formResetCallback() {
		this.checked = this.hasAttribute('checked')
	}
	private onInput(event: Event) {
		this.checked = (event.target as HTMLInputElement).checked
	}
	// The inner change does not leave the shadow root: the element sends its own.
	private onChange() {
		this.dispatchEvent(new Event('change', { bubbles: true, composed: true }))
		this.emit('checked-change', { value: this.checked })
	}

	render() {
		const id = this.inputId
		const text = this.label || this.hasSlot() || this.hint
		return html`<label for=${id} class="contents">
			<span class="ds-checkbox">
				<input id=${id} type="checkbox" .checked=${live(this.checked)} .indeterminate=${this.indeterminate} name=${ifDefined(this.name)} value=${ifDefined(this.value)} ?disabled=${this.inactive} ?required=${this.required} aria-invalid=${ifDefined(this.invalid ? 'true' : undefined)} aria-describedby=${ifDefined(this.hint ? `${id}-hint` : undefined)} @input=${this.onInput} @change=${this.onChange}>
				${this.indeterminate
					? html`<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4 8h8"></path></svg>`
					: html`<svg viewBox="0 0 16 16" aria-hidden="true"><path d="M3.5 8.5 6.5 11.5 12.5 4.5" pathLength="1"></path></svg>`}
			</span>
			${text
				? html`<span class="flex min-w-0 flex-col">
						<span><slot>${this.label}</slot></span>
						${this.hint ? html`<span id=${`${id}-hint`} class="type-caption text-fg-muted">${this.hint}</span>` : nothing}
					</span>`
				: html`<slot></slot>`}
		</label>`
	}
}

define('checkbox', Checkbox)
elements/components/ui/checkbox.css
/* Checkbox.tsx's styles, with the row (.ds-checkrow, the React root) as the host. */
/* The host rules are !important: the page's preflight and scoped base (padding: 0, border: 0, the root's type) win over a plain :host rule, and React's unlayered rule wins over them, as an important shadow rule does. */
:host { display: inline-flex !important; min-height: var(--ds-size-control-sm) !important; align-items: flex-start !important; gap: var(--ds-space-md) !important; padding-block: 6px !important; color: var(--ds-color-fg) !important; font-family: var(--ds-font-text) !important; font-size: var(--ds-text-ui) !important; line-height: var(--ds-text-ui-leading) !important; cursor: pointer !important; }
:host([disabled]) { color: var(--ds-color-fg-faint) !important; cursor: not-allowed !important; }
.ds-checkbox { position: relative; display: inline-grid; width: 16px; height: 16px; flex-shrink: 0; margin-top: 2px; }
.ds-checkbox > * { grid-area: 1 / 1; }
.ds-checkbox > input { width: 16px; height: 16px; margin: 0; border: var(--ds-border-hairline) solid var(--ds-color-edge-strong); border-radius: var(--ds-radius-sm); background: var(--ds-color-surface); appearance: none; cursor: inherit; transition: border-color var(--ds-duration-micro) var(--ds-easing-standard), background-color var(--ds-duration-micro) var(--ds-easing-standard); }
.ds-checkbox > input:is(:checked, :indeterminate) { border-color: var(--ds-color-action-primary); background: var(--ds-color-action-primary); }
.ds-checkbox > input:focus-visible { outline: var(--ds-border-focus) solid var(--ds-color-edge-focus); outline-offset: var(--ds-border-focus); }
.ds-checkbox > input[aria-invalid="true"]:not(:checked) { border-color: var(--ds-color-action-danger); }
.ds-checkbox > input:disabled { border-color: var(--ds-color-edge); background: var(--ds-color-action-disabled); }
.ds-checkbox > input:disabled:is(:checked, :indeterminate) { border-color: var(--ds-color-edge-strong); background: var(--ds-color-edge-strong); }
.ds-checkbox > svg { width: 16px; height: 16px; fill: none; stroke: var(--ds-color-action-primary-fg); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
.ds-checkbox > svg path[pathLength] { stroke-dasharray: 1; stroke-dashoffset: 1; transition: stroke-dashoffset var(--ds-duration-micro) var(--ds-easing-standard); }
.ds-checkbox > input:checked + svg path[pathLength] { stroke-dashoffset: 0; transition: stroke-dashoffset var(--ds-duration-glide) var(--ds-easing-out); }
.ds-checkbox > input:not(:indeterminate) + svg path:not([pathLength]) { opacity: 0; }
@media (hover: hover) and (pointer: fine) { :host(:hover) .ds-checkbox > input:not(:disabled, :checked, :indeterminate) { border-color: var(--ds-color-action-secondary-edge-hover) !important; } }
@media (pointer: coarse), (max-width: 767px) { :host { min-height: var(--ds-size-control-touch) !important; align-items: center !important; padding-block: 8px !important; font-size: var(--ds-text-body) !important; } .ds-checkbox { margin-top: 0; } }
@media (prefers-reduced-motion: reduce) { .ds-checkbox > svg path[pathLength], .ds-checkbox > input:checked + svg path[pathLength] { transition: none; } }

Reference: Derived from the guidelines: White on Black for what is on, neutral hairlines, the 4px small corner, DM Sans labels. shadcn's checkbox for anatomy and the indeterminate state..