Menu

Components

Checkbox

A box that is on or off. Built on react-aria-components.

Introduction

Use a checkbox when the user can turn each option on or off on its own: accepting terms, or picking any number of items from a short list. When exactly one option must be chosen, use a radio group or Select instead.

  • Keyboard support (Space toggles) and screen reader support come from react-aria-components. Clicking the label toggles it too.
  • A description under the label, an indeterminate state, and an error message when it is invalid.
  • Need several related boxes with one value? See Checkbox Group.
  • Works in a form: give it a name and value.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/checkbox-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for Checkbox. The box and the label read the state of the checkbox
// (selected, focused, invalid...) from data attributes on the root, which
// react-aria sets, through the `group/checkbox` name.
export const checkboxStyles = tv({
  slots: {
    root: [
      "group/checkbox relative flex items-start gap-2.5 cursor-pointer",
      "data-disabled:cursor-not-allowed data-disabled:opacity-50",
    ],
    box: [
      "flex shrink-0 items-center justify-center rounded-[5px] border bg-bg text-primary-fg transition-colors",
      "group-data-hovered/checkbox:border-fg/50",
      "group-data-selected/checkbox:border-primary group-data-selected/checkbox:bg-primary",
      "group-data-indeterminate/checkbox:border-primary group-data-indeterminate/checkbox:bg-primary",
      "group-data-focus-visible/checkbox:ring-2 group-data-focus-visible/checkbox:ring-ring group-data-focus-visible/checkbox:ring-offset-2 group-data-focus-visible/checkbox:ring-offset-bg",
      "group-data-invalid/checkbox:border-danger group-data-invalid/checkbox:group-data-selected/checkbox:bg-danger group-data-invalid/checkbox:group-data-indeterminate/checkbox:bg-danger",
      "group-data-invalid/checkbox:group-data-selected/checkbox:text-danger-fg group-data-invalid/checkbox:group-data-indeterminate/checkbox:text-danger-fg",
    ],
    label: "font-medium leading-snug",
    description: "text-muted-fg leading-snug",
    error: "text-danger leading-snug",
  },
  variants: {
    size: {
      sm: {
        root: "text-sm",
        box: "mt-[3px] size-3.5 [&_svg]:size-2.5",
        description: "text-xs",
        error: "text-xs",
      },
      md: {
        root: "text-sm",
        box: "mt-0.5 size-4 [&_svg]:size-3",
        description: "text-sm",
        error: "text-sm",
      },
      lg: {
        root: "text-base",
        box: "mt-0.5 size-5 [&_svg]:size-3.5",
        description: "text-sm",
        error: "text-sm",
      },
    },
  },
  defaultVariants: { size: "md" },
});

2. Add the group context

Checkbox reads its size from an enclosing Checkbox Group through this small file. It works fine without a group.

src/types/checkbox-group-context.tsShow code
import { createContext, useContext } from "react";
import type { VariantProps } from "tailwind-variants";
import type { checkboxStyles } from "./checkbox-styles";

/** Defaults a CheckboxGroup passes down to the checkboxes inside it. */
export type CheckboxGroupContextValue = Pick<
  VariantProps<typeof checkboxStyles>,
  "size"
>;

const CheckboxGroupContext = createContext<CheckboxGroupContextValue | null>(
  null,
);

export const CheckboxGroupProvider = CheckboxGroupContext.Provider;

/** The enclosing CheckboxGroup's defaults, or null outside of one. */
export function useCheckboxGroup() {
  return useContext(CheckboxGroupContext);
}

3. Add the Checkbox file

src/components/ui/checkbox/checkbox.tsxShow code
"use client";

import { type ReactNode, useId } from "react";
import {
  Checkbox as AriaCheckbox,
  type CheckboxProps as AriaCheckboxProps,
} from "react-aria-components";
import { CheckIcon, MinusIcon } from "@/components/icons";
import { cn } from "@/lib/cn";
import { useCheckboxGroup } from "@/types/checkbox-group-context";
import { checkboxStyles } from "@/types/checkbox-styles";

export interface CheckboxProps
  extends Omit<AriaCheckboxProps, "children" | "className"> {
  /** The text next to the box. */
  children?: ReactNode;
  /** A smaller line under the label. */
  description?: ReactNode;
  /** Shown under the label while `isInvalid` is `true`. */
  errorMessage?: ReactNode;
  size?: "sm" | "md" | "lg";
  className?: string;
}

/**
 * A box that is on or off. Built on react-aria's Checkbox, so keyboard
 * support, screen reader support and form submission (`name`, `value`) come
 * from there. Give it an accessible name: text in `children`, or `aria-label`.
 *
 * Put several inside a `CheckboxGroup` to share one value, label and error.
 *
 * Set `isIndeterminate` for the "some, not all" state, for example on a
 * "select all" box. It shows a dash and is just a look: the checkbox still
 * toggles between selected and not selected.
 *
 * @example
 * <Checkbox defaultSelected description="We send at most one a week.">
 *   Email me updates
 * </Checkbox>
 */
export function Checkbox({
  children,
  description,
  errorMessage,
  size,
  isInvalid,
  className,
  ...props
}: CheckboxProps) {
  // Same channel CheckboxGroup uses, so a checkbox reads its size from it.
  const group = useCheckboxGroup();
  const styles = checkboxStyles({ size: size ?? group?.size });
  const descriptionId = useId();
  const errorId = useId();
  const showError = Boolean(isInvalid && errorMessage);
  const describedBy =
    [description ? descriptionId : null, showError ? errorId : null]
      .filter(Boolean)
      .join(" ") || undefined;

  return (
    <AriaCheckbox
      aria-describedby={describedBy}
      {...props}
      isInvalid={isInvalid}
      className={cn(styles.root(), className)}
    >
      {({ isSelected, isIndeterminate }) => (
        <>
          <span aria-hidden="true" className={styles.box()}>
            {isIndeterminate ? (
              <MinusIcon strokeWidth={3} />
            ) : isSelected ? (
              <CheckIcon strokeWidth={3} />
            ) : null}
          </span>
          {children || description || showError ? (
            <span className="flex min-w-0 flex-col gap-0.5">
              {children ? (
                <span className={styles.label()}>{children}</span>
              ) : null}
              {description ? (
                <span id={descriptionId} className={styles.description()}>
                  {description}
                </span>
              ) : null}
              {showError ? (
                <span id={errorId} className={styles.error()}>
                  {errorMessage}
                </span>
              ) : null}
            </span>
          ) : null}
        </>
      )}
    </AriaCheckbox>
  );
}

It imports CheckIcon and MinusIcon from @/components/icons. Add those icons, or swap them for your own.

4. Use it

import { Checkbox } from "@/components/ui/checkbox/checkbox";

Anatomy

A checkbox is a box with a label.

<Checkbox description="We send at most one a week.">
  Email me updates
</Checkbox>
PartRendered asNotes
BoxspanThe square. Shows a check when selected, a dash when indeterminate.
LabelspanThe text next to the box. Clicking it toggles the checkbox.
DescriptionspanA smaller line under the label.
ErrorspanUnder the label while the checkbox is invalid.

A checkbox without text needs an aria-label so a screen reader can name it.

Examples

Live previews with code you can copy.

Usage

Description

A smaller line under the label.

Indeterminate

A dash for “some, not all”. It is only a look: the value is still on or off.

Uncontrolled

Let the component keep its own state. Start with defaultSelected, and give it a name and value to read it from a form.

Controlled

Keep the state yourself with isSelected and onChange.

isSelected: true

Sizes

Disabled

Disable a checkbox with isDisabled.

Validation

Set isInvalid with an errorMessage. The box gets a red border and the message shows under the label.

Component API

Checkbox takes the props below, plus everything the react-aria Checkbox accepts.

PropTypeDefault
childrenReactNode-
descriptionReactNode-
errorMessageReactNode-
isSelectedboolean-
defaultSelectedbooleanfalse
onChange(isSelected: boolean) => void-
isIndeterminatebooleanfalse
valuestring- (needed in a group)
namestring-
size"sm" | "md" | "lg""md"
isDisabledbooleanfalse
isInvalidbooleanfalse
isRequiredbooleanfalse
aria-labelstring- (when there is no text)

To use several related checkboxes with one value, see Checkbox Group. Inside one, a checkbox needs a value.