# Checkbox
One yes or no, ticked by a person or an agent.
Source page: https://dinachi.dev/docs/components/checkbox

## Installation
```bash
npx @dinachi/cli@latest add checkbox
```
Adds to your project:
- `components/ui/checkbox/checkbox.tsx`
- `components/ui/checkbox/index.ts`
Installs:
- `@base-ui/react` ^1.9.0
- `lucide-react` ^0.552.0

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

export function TermsCheckbox() {
  return (
    <div className="flex items-center gap-2">
      <Checkbox id="terms" name="terms" />
      <label htmlFor="terms" className="text-sm">
        Accept terms and conditions
      </label>
    </div>
  )
}
```

## Examples

### Default
A checkbox named by its label.
```tsx
import { Checkbox } from '@/components/ui/checkbox';

export function Example() {
  return (
    <div className="flex items-center space-x-2">
      <Checkbox id="terms" />
      <label htmlFor="terms" className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
        Accept terms and conditions
      </label>
    </div>
  );
}
```

### States
Controlled, checked and disabled checkboxes.
```tsx
import React from 'react';
import { Checkbox } from '@/components/ui/checkbox';

export function Example() {
  const [checked, setChecked] = React.useState(false);
  const [indeterminate, setIndeterminate] = React.useState('indeterminate');

  return (
    <div className="space-y-4">
      <div className="flex items-center space-x-2">
        <Checkbox checked={checked} onCheckedChange={setChecked} />
        <label className="text-sm font-medium">Controlled checkbox</label>
      </div>
      <div className="flex items-center space-x-2">
        <Checkbox checked={indeterminate} onCheckedChange={setIndeterminate} />
        <label className="text-sm font-medium">Indeterminate checkbox</label>
      </div>
      <div className="flex items-center space-x-2">
        <Checkbox disabled />
        <label className="text-sm font-medium text-muted-foreground">Disabled checkbox</label>
      </div>
    </div>
  );
}
```

## Notes

### Labels and peer classes
The box sits in a wrapper span with the hidden input. A `<label htmlFor>` beside it works, but Tailwind `peer-*` classes on that label cannot see the box: the label is a sibling of the wrapper, not the box.

### In a group
Inside a [CheckboxGroup](/docs/components/checkbox-group), give each Checkbox a `value`. The group's value decides which are ticked, and changes go through the group's `onValueChange` instead of `onCheckedChange`.

## API reference
Props marked **agent** change what an agent reads or may do.

### Checkbox
The box, indicator and hidden form input.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `checked` | `boolean` | - | Controlled checked state. |
| `defaultChecked` | `boolean` | `false` | Starting state when uncontrolled. |
| `onCheckedChange` **agent** | `(checked, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `indeterminate` **agent** | `boolean` | `false` | Shows the mixed state. The agent reads `checked` as `"mixed"`. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `readOnly` **agent** | `boolean` | `false` | Shows the state, refuses any change. |
| `required` | `boolean` | `false` | Must be ticked before the form submits. |
| `name` | `string` | - | Submits the checkbox with a form. |
| `value` **agent** | `string` | - | Identifies it in a `CheckboxGroup`; submitted when ticked. |
| `parent` **agent** | `boolean` | `false` | Ticks or clears every checkbox in its `CheckboxGroup`. Needs `allValues` on the group. |
| `id` | `string` | - | The id a `<label htmlFor>` points at. |

## Agent
Inside an `AgentProvider`, Checkbox appears in `agent.snapshot()` as `checkbox`.
Reads:
- `label`: The label pointing at it, or its aria-label.
- `checked`: true, false, or "mixed" when indeterminate.
- `disabled`: True when the checkbox is blocked.
Actions:
- `toggle()`: Ticks it, or clears it when ticked. A mixed box becomes ticked.
- `setChecked(true)`: Sets the state. Setting the current state succeeds as a no-op.
An agent's change runs through `onCheckedChange` like anyone's. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and the agent is told the app refused. In a group it goes through the group's `onValueChange` instead. A disabled or `readOnly` checkbox refuses on its own.
```ts
await agent.act({
  steps: [{ ref: "Accept terms", action: "setChecked", args: [true] }],
})
```

## Accessibility
- The box has role="checkbox" with aria-checked set to true, false or mixed.
- Name it with a `<label htmlFor>` on its id, or aria-label. The agent reads it too.
- A hidden input submits the value with a native form.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` | Toggles the checkbox |

## Source
`components/ui/checkbox/checkbox.tsx`
```tsx
import * as React from "react";
import { Checkbox as BaseCheckbox } from '@base-ui/react/checkbox';
import { cn } from "@/lib/utils";
import { Check } from "lucide-react";
import {
  AgentGroupContext,
  agentChecked,
  changeAsAgent,
  useAgentControl,
  useAgentItem,
  useAgentState,
  useMergedRef,
} from "@/components/ui/agent";

type CheckboxProps = React.ComponentPropsWithoutRef<typeof BaseCheckbox.Root>;

function ariaChecked(el: Element | null): boolean | "mixed" {
  const state = el?.getAttribute("aria-checked");
  return state === "mixed" ? "mixed" : state === "true";
}

/**
 * Base UI's checkbox, holding its own checked state so an agent can check it the way a
 * parent would. Controlled use is unchanged, and `onCheckedChange` sees the agent's
 * changes first and can cancel them. In a group the group's value decides, so the agent
 * goes through the group's `onValueChange` instead.
 */
const Checkbox = React.forwardRef<
  React.ComponentRef<typeof BaseCheckbox.Root>,
  CheckboxProps
>(({ className, checked: checkedProp, defaultChecked = false, onCheckedChange, ...props }, ref) => {
  const [checked, change] = useAgentState<boolean, BaseCheckbox.Root.ChangeEventDetails>(
    checkedProp,
    defaultChecked,
    onCheckedChange
  );
  const group = React.useContext(AgentGroupContext);
  const element = React.useRef<HTMLElement | null>(null);
  const mergedRef = useMergedRef(ref, element);
  const grouped = group && (props.parent || props.value !== undefined) ? group : null;
  useAgentItem(grouped?.items ?? null, element, props.parent ? undefined : props.value);

  useAgentControl(() => {
    const now = ariaChecked(element.current);
    const set = (next: boolean) => {
      if (props.readOnly) return "The checkbox is read-only.";
      if (next === now) return undefined;
      return grouped ? grouped.set(props.parent ? undefined : props.value, next) : changeAsAgent(change, next);
    };
    return {
      kind: "checkbox",
      element: element.current,
      checked: now,
      disabled: props.disabled,
      actions: {
        toggle: () => set(now !== true),
        setChecked: (value: unknown) => set(agentChecked(value)),
      },
    };
  });

  return (
  <span className="relative inline-flex [&>input]:!absolute">
    <BaseCheckbox.Root
      ref={mergedRef}
      data-slot="checkbox"
      className={cn(
        "peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
        "data-[checked]:bg-primary data-[checked]:text-primary-foreground",
        className
      )}
      {...props}
      checked={checked}
      onCheckedChange={change}
    >
      <BaseCheckbox.Indicator
        className={cn("flex items-center justify-center text-current")}
      >
        <Check className="h-4 w-4" />
      </BaseCheckbox.Indicator>
    </BaseCheckbox.Root>
  </span>
  );
});
Checkbox.displayName = "Checkbox";

export { Checkbox };
```
