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.
API Reference
Properties
Property | Type | Default | Description |
---|---|---|---|
checked | boolean | false | Whether the checkbox is checked. |
indeterminate | boolean | false | Whether the checkbox is in an indeterminate state. |
disabled | boolean | false | Whether the checkbox is disabled. |
required | boolean | false | Whether the checkbox is required. |
name | string | undefined | The name of the checkbox when used in a form. |
value | string | undefined | The value of the checkbox when used in a form. |
class | string | undefined | Additional CSS classes to apply to the checkbox. |
ref | HTMLButtonElement | null | Reference to the underlying HTML button element. |
Events
The Checkbox component forwards all standard HTML button events, as it’s based on a button element:
Event | Description |
---|---|
click | Fires when the checkbox is clicked. |
focus | Fires when the checkbox receives focus. |
blur | Fires when the checkbox loses focus. |
change | Fires 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.