Checkbox

The Checkbox component allows users to select one or multiple items from a set. It can also be used to turn an option on or off.

Usage

<script>
  import { Checkbox } from "$lib/components/ui/checkbox";
</script>

<Checkbox />

Examples

Basic Checkbox

A simple checkbox that can be checked or unchecked.

Checkbox with Label

A checkbox with an associated label for better accessibility.

Checked State

A checkbox in its checked state.

Indeterminate State

A checkbox in its indeterminate state, useful for parent-child checkbox relationships.

Disabled State

A checkbox that cannot be interacted with.

Checkbox Items

Using checkboxes in a list format for selecting multiple options.

Form Example

Using checkboxes within a form.

Subscription preferences

API Reference

Properties

PropertyTypeDefaultDescription
checkedbooleanfalseWhether the checkbox is checked.
indeterminatebooleanfalseWhether the checkbox is in an indeterminate state.
disabledbooleanfalseWhether the checkbox is disabled.
requiredbooleanfalseWhether the checkbox is required.
namestringundefinedThe name of the checkbox when used in a form.
valuestringundefinedThe value of the checkbox when used in a form.
classstringundefinedAdditional CSS classes to apply to the checkbox.
refHTMLButtonElementnullReference to the underlying HTML button element.

Events

The Checkbox component forwards all standard HTML button events, as it’s based on a button element:

EventDescription
clickFires when the checkbox is clicked.
focusFires when the checkbox receives focus.
blurFires when the checkbox loses focus.
changeFires when the checkbox state changes.

Implementation

The Checkbox component is built on top of bits-ui primitives. It provides custom styling for checked, unchecked, and indeterminate states, with appropriate focus and hover effects:

// Checkbox styling
"border-primary focus-visible:ring-ring data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground peer box-content size-4 shrink-0 rounded-sm border shadow focus-visible:outline-none focus-visible:ring-1 disabled:cursor-not-allowed disabled:opacity-50 data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-50"

The component includes built-in icons for the different states, with a check mark for checked state and a minus sign for indeterminate state.

This component is built with accessibility in mind, supporting keyboard navigation, screen readers, and proper ARIA attributes. It integrates well with labels by using the peer element in CSS.