# Checkbox

A control that lets the user toggle between checked and not checked.

```tsx
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { HStack, VStack } from "@/components/ui/stack"
import { Text } from "@/components/ui/text"
import { widths } from "@/theme/widths"

export default function CheckboxDemo() {
  return (
    <VStack gap={6} xstyle={widths.sm}>
      <HStack gap={2} align="center">
        <Checkbox id="terms-checkbox" name="terms-checkbox" />
        <Label htmlFor="terms-checkbox">Agree to the usage policy</Label>
      </HStack>
      <HStack gap={2} align="start">
        <Checkbox id="terms-checkbox-2" name="terms-checkbox-2" defaultChecked />
        <VStack gap={1}>
          <Label htmlFor="terms-checkbox-2">Agree to the usage policy</Label>
          <Text size="sm" tone="muted" weight="normal">
            The policy covers how lab data is stored.
          </Text>
        </VStack>
      </HStack>
      <HStack gap={2} align="center">
        <Checkbox id="toggle-checkbox" name="toggle-checkbox" disabled />
        <Label htmlFor="toggle-checkbox" disabled>
          Send weekly summaries
        </Label>
      </HStack>
      <Label>
        <Checkbox name="toggle-checkbox-2" />
        <VStack gap={1}>
          <span>Send weekly summaries</span>
          <Text size="sm" tone="muted" weight="normal">
            A short digest of the week&apos;s runs, sent on Mondays.
          </Text>
        </VStack>
      </Label>
    </VStack>
  )
}
```

## Installation

**Command**

```bash
npx shadcn@latest add @arene/checkbox
```

Needs the [arene setup](https://www.arene.style/docs/installation) first.

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex @phosphor-icons/react
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation), and paste `states.ts` and
   `state-styles.ts` from the same page. The checkbox imports both. It also needs
   `interop.css`, which sizes the tick. The
   examples caption it with a [Label](https://www.arene.style/docs/components/label).

   Paste `field-state.ts` from the same installation page.

3. Paste this source into the file named in its title.

   ```tsx title="components/ui/checkbox.tsx"
   "use client"

   import { use, type CSSProperties } from "react"
   import { Checkbox as CheckboxPrimitive } from "@base-ui/react/checkbox"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { CheckIcon } from "@phosphor-icons/react/dist/csr/Check"
   import { MinusIcon } from "@phosphor-icons/react/dist/csr/Minus"

   import { stateStyles } from "@/lib/state-styles"
   import { FieldStateContext } from "@/lib/field-state"
   import { states } from "@/theme/states"
   import { duration, ease, radius, space } from "@/theme/tokens.stylex"

   const styles = stylex.create({
     root: {
       position: "relative",
       display: "flex",
       alignItems: "center",
       justifyContent: "center",
       flexShrink: 0,
       width: space.s4,
       height: space.s4,
       borderRadius: radius.sm,
       borderWidth: 1,
       borderStyle: "solid",
       transitionProperty: "color, background-color, border-color, box-shadow",
       transitionDuration: duration.color,
       transitionTimingFunction: ease.standard,
       "--arene-icon-size": space.s3_5,
       "::after": {
         content: '""',
         position: "absolute",
         insetInline: `calc(-1 * ${space.s3})`,
         insetBlock: `calc(-1 * ${space.s2})`,
       },
     },
     indicator: {
       display: "flex",
       alignItems: "center",
       justifyContent: "center",
       transitionProperty: "opacity, transform",
       transitionDuration: {
         default: duration.color,
         "@media (prefers-reduced-motion: reduce)": "0s",
       },
       transitionTimingFunction: ease.standard,
     },
     indicatorHidden: { opacity: 0, transform: "scale(0.6)" },
   })

   const checkboxStyles = {
     root: styles.root,
     indicator: styles.indicator,
     indicatorHidden: styles.indicatorHidden,
     choice: states.choice,
     checked: states.choiceChecked,
     disabled: states.disabled,
     invalid: states.invalidRing,
   }

   type CheckboxProps = Omit<CheckboxPrimitive.Root.Props, "className" | "style"> & {
     xstyle?: StyleXStyles
     style?: CSSProperties
     className?: string
   }

   function Checkbox({ xstyle, style, className, indeterminate, ...props }: CheckboxProps) {
     const fieldState = use(FieldStateContext)
     return (
       <CheckboxPrimitive.Root
         data-slot="checkbox"
         indeterminate={indeterminate}
         {...props}
         {...stateStyles(
           (state) => [
             styles.root,
             states.choice,
             states.focusRing,
             (state.valid === false ||
               fieldState?.valid === false ||
               props["aria-invalid"] === true ||
               props["aria-invalid"] === "true") &&
               states.invalidRing,
             (state.checked || state.indeterminate) && states.choiceChecked,
             state.disabled && states.disabled,
             xstyle,
           ],
           { className, style, hook: "arene-icons" },
         )}
       >
         <CheckboxPrimitive.Indicator
           data-slot="checkbox-indicator"
           {...stateStyles((state) => [
             styles.indicator,
             (state.transitionStatus === "starting" || state.transitionStatus === "ending") &&
               styles.indicatorHidden,
           ])}
           render={(indicatorProps, state) => (
             <span {...indicatorProps}>
               {state.indeterminate ? (
                 <MinusIcon aria-hidden="true" />
               ) : (
                 <CheckIcon aria-hidden="true" />
               )}
             </span>
           )}
         />
       </CheckboxPrimitive.Root>
     )
   }

   export { Checkbox, checkboxStyles }
   ```

4. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import { Checkbox } from "@/components/ui/checkbox"
```

```tsx
<Checkbox id="terms" />
<Label htmlFor="terms">Agree to the usage policy</Label>
```

Lay a checkbox and its label out in an `HStack`, or in a horizontal
[Field](https://www.arene.style/docs/components/field) for automatic label association.

## Checked state

Use `defaultChecked` for an uncontrolled checkbox, or `checked` and
`onCheckedChange` to control it.

```tsx
import { useState } from "react"

export function Example() {
  const [checked, setChecked] = useState(false)

  return <Checkbox checked={checked} onCheckedChange={setChecked} />
}
```

## Invalid state

Set `invalid` on `Field` or `aria-invalid` on a bare checkbox. Both show the destructive border and ring.

```tsx
import { Checkbox } from "@/components/ui/checkbox"
import { Field, FieldLabel, FieldError } from "@/components/ui/field"
import { Label } from "@/components/ui/label"
import { VStack } from "@/components/ui/stack"

export default function CheckboxInvalid() {
  return (
    <VStack gap={5} width="100%" maxWidth="24rem">
      <VStack gap={2}>
        <Label htmlFor="checkbox-invalid-bare">Agree to the usage policy</Label>
        <Checkbox
          id="checkbox-invalid-bare"
          aria-invalid
          aria-describedby="checkbox-invalid-bare-error"
        />
        <FieldError id="checkbox-invalid-bare-error">
          Agree to the usage policy to continue.
        </FieldError>
      </VStack>
      <Field invalid>
        <FieldLabel>Agree to the usage policy</FieldLabel>
        <Checkbox />
        <FieldError>Agree to the usage policy to continue.</FieldError>
      </Field>
    </VStack>
  )
}
```

## Basic

Pair the checkbox with a `Label` in an `HStack`.

```tsx
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { HStack } from "@/components/ui/stack"

export default function CheckboxBasic() {
  return (
    <HStack gap={2} align="center">
      <Checkbox id="terms-checkbox-basic" name="terms-checkbox-basic" />
      <Label htmlFor="terms-checkbox-basic">Agree to the usage policy</Label>
    </HStack>
  )
}
```

## Description

Stack the label and a line of helper text in a `VStack` beside the checkbox,
and align the row to `start` so the box sits on the first line.

```tsx
import * as stylex from "@stylexjs/stylex"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { HStack, VStack } from "@/components/ui/stack"
import { Text } from "@/components/ui/text"

const styles = stylex.create({
  field: { width: "100%", maxWidth: "18rem" },
})

export default function CheckboxDescription() {
  return (
    <HStack gap={2} align="start" xstyle={styles.field}>
      <Checkbox id="terms-checkbox-desc" name="terms-checkbox-desc" defaultChecked />
      <VStack gap={1}>
        <Label htmlFor="terms-checkbox-desc">Agree to the usage policy</Label>
        <Text size="sm" tone="muted">
          The policy covers how lab data is stored, shared and deleted.
        </Text>
      </VStack>
    </HStack>
  )
}
```

## Disabled

Set `disabled` on `Field` to disable its control and dim its label, or on a bare control directly.

```tsx
import { Checkbox } from "@/components/ui/checkbox"
import { Field, FieldLabel } from "@/components/ui/field"
export default function CheckboxDisabled() {
  return (
    <Field orientation="horizontal" disabled>
      <Checkbox name="notifications" />
      <FieldLabel>Send weekly summaries</FieldLabel>
    </Field>
  )
}
```

## Group

Use [Checkbox Group](https://www.arene.style/docs/components/checkbox-group) to share selection state and Field validation.

```tsx
import { Checkbox } from "@/components/ui/checkbox"
import { CheckboxGroup } from "@/components/ui/checkbox-group"
import { Field, FieldDescription, FieldItem, FieldLabel } from "@/components/ui/field"
const items = [
  { value: "raw-data", label: "Raw data" },
  { value: "plots", label: "Plots" },
  { value: "lab-notes", label: "Lab notes" },
  { value: "instrument-logs", label: "Instrument logs" },
]
export default function CheckboxGroupExample() {
  return (
    <Field name="export-items">
      <FieldLabel nativeLabel={false} render={<div />}>
        Include in the export:
      </FieldLabel>
      <FieldDescription>Choose what goes into the exported notebook.</FieldDescription>
      <CheckboxGroup defaultValue={["raw-data", "plots"]}>
        {items.map(({ value, label }) => (
          <FieldItem key={value}>
            <FieldLabel>
              <Checkbox value={value} />
              {label}
            </FieldLabel>
          </FieldItem>
        ))}
      </CheckboxGroup>
    </Field>
  )
}
```

## Indeterminate

Use `parent` inside a controlled [Checkbox Group](https://www.arene.style/docs/components/checkbox-group) with `allValues` to derive the checked and indeterminate states automatically.

Use the `indeterminate` prop for a parent that controls a set of children. It
draws a dash in place of the tick and is independent of `checked`.

```tsx
"use client"

import { useState } from "react"
import * as stylex from "@stylexjs/stylex"
import { Checkbox } from "@/components/ui/checkbox"
import { Label } from "@/components/ui/label"
import { HStack, VStack } from "@/components/ui/stack"
import { space } from "@/theme/tokens.stylex"

const styles = stylex.create({
  children: { paddingInlineStart: space.s6 },
})

const permissions = [
  { id: "read", label: "Read" },
  { id: "write", label: "Write" },
  { id: "deploy", label: "Deploy" },
]

export default function CheckboxIndeterminate() {
  const [granted, setGranted] = useState<string[]>(["read"])

  const all = granted.length === permissions.length
  const some = granted.length > 0 && !all

  return (
    <VStack gap={3}>
      <HStack gap={2} align="center">
        <Checkbox
          id="permissions-all"
          checked={all}
          indeterminate={some}
          onCheckedChange={(checked) => setGranted(checked ? permissions.map((p) => p.id) : [])}
        />
        <Label htmlFor="permissions-all">All permissions</Label>
      </HStack>
      <VStack gap={3} xstyle={styles.children}>
        {permissions.map((permission) => (
          <HStack key={permission.id} gap={2} align="center">
            <Checkbox
              id={`permissions-${permission.id}`}
              checked={granted.includes(permission.id)}
              onCheckedChange={(checked) =>
                setGranted((current) =>
                  checked
                    ? [...current, permission.id]
                    : current.filter((id) => id !== permission.id),
                )
              }
            />
            <Label htmlFor={`permissions-${permission.id}`}>{permission.label}</Label>
          </HStack>
        ))}
      </VStack>
    </VStack>
  )
}
```

> **Note**
>
> `indeterminate` is a display state. Clicking the checkbox still fires
> `onCheckedChange` with the opposite of `checked`, so decide what a click on a
> mixed parent means and set `checked` from that.

## API reference

Pass `render` to replace a part's element or compose it with another component.

`Checkbox` wraps the Base UI `Checkbox.Root` and renders its `Indicator`
inside. See the [Base UI reference](https://base-ui.com/react/components/checkbox)
for the full list of props.

### Checkbox

| Prop              | Type                                  | Default |
| ----------------- | ------------------------------------- | ------- |
| `checked`         | `boolean`                             | —       |
| `defaultChecked`  | `boolean`                             | `false` |
| `onCheckedChange` | `(checked: boolean, details) => void` | —       |
| `indeterminate`   | `boolean`                             | `false` |
| `disabled`        | `boolean`                             | `false` |
| `readOnly`        | `boolean`                             | `false` |
| `required`        | `boolean`                             | `false` |
| `name`            | `string`                              | —       |
| `value`           | `string`                              | —       |
| `id`              | `string`                              | —       |
| `inputRef`        | `Ref<HTMLInputElement>`               | —       |
| `xstyle`          | `StyleXStyles`                        | —       |
| `style`           | `CSSProperties`                       | —       |
| `className`       | `string`                              | —       |

The root is a `<span role="checkbox">`. Base UI renders a hidden `<input>`
beside it that carries `id`, `name` and `value`. A label's `htmlFor` and a
form submission reach the control through that input.

### checkboxStyles

The style maps behind the component. Spread them onto any element.

| Key               | What it is                                     |
| ----------------- | ---------------------------------------------- |
| `root`            | The box: size, border width, corner, hit area  |
| `indicator`       | The tick's box and its fade                    |
| `indicatorHidden` | The tick faded out and scaled down             |
| `choice`          | The hairline edge and fill at a choice's size  |
| `checked`         | The flat primary fill and inverted tick colour |
| `disabled`        | The dimmed, non-interactive state              |
| `invalid`         | The destructive border and ring                |

`root` carries no colour and no focus ring. Everything else comes from `states`
in `theme/states.ts`. Merge `choice`, then `states.focusRing`. Merge `invalid`
before `checked`, so a ticked invalid box keeps the primary fill and shows only
the destructive ring.

### Data attributes

| Attribute                                         | On              | Effect                                              |
| ------------------------------------------------- | --------------- | --------------------------------------------------- |
| `data-slot="checkbox"`                            | the root        | Targets the box from a parent                       |
| `data-slot="checkbox-indicator"`                  | the indicator   | Targets the animated indicator                      |
| `data-checked`, `data-unchecked`                  | root, indicator | Base UI writes them                                 |
| `data-parent`                                     | root            | Controls the group selection                        |
| `data-indeterminate`                              | root, indicator | Base UI writes it                                   |
| `data-disabled`, `data-readonly`, `data-required` | root, indicator | Base UI writes them                                 |
| `data-starting-style`, `data-ending-style`        | the indicator   | Base UI writes them while the tick enters or leaves |
