Menu

Components

Toggle

A button that stays on or off. Built on react-aria-components, with the same look as Button.

Introduction

Use Toggle for a setting that is either on or off and takes effect right away: bookmark this, pin that, show compact rows. It looks like a Button, and the on state is filled with the primary color so the difference is obvious at a glance.

  • Uncontrolled with defaultSelected, or controlled with isSelected and onChange.
  • Announced to assistive technology as a toggle button through aria-pressed.
  • children can be a function, so the icon or text can change with the state.
  • Every Button size, an icon-only mode, and it picks up the defaults of a surrounding ButtonGroup.

Installation

centerUI has no CLI or registry yet: components are copied into your project. Toggle reuses the Button styles, so it needs everything Button needs.

# 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

Add Button first (see its Manual installation), then follow the steps below.

Manual installation

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

1. Add the Toggle files

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

// A toggle is a Button with a "selected" look: the selected one is filled with
// the primary color. Used by Toggle, and so by every ToggleGroup item. Hover and press keep the selected color, so
// the two states never fight over the background.
export const toggleStyles = tv({
  extend: buttonStyles,
  base: [
    "data-selected:border-primary data-selected:bg-primary data-selected:text-primary-fg",
    "data-selected:data-hovered:bg-primary/90 data-selected:data-pressed:bg-primary/80",
  ],
  defaultVariants: {
    variant: "outline",
  },
});
src/components/ui/toggle/toggle.tsxShow code
"use client";

import { ToggleButton, type ToggleButtonProps } from "react-aria-components";
import type { VariantProps } from "tailwind-variants";
import { cx } from "@/lib/primitive";
import { useButtonGroup } from "@/types/button-group-context";
import { toggleStyles } from "@/types/toggle-styles";

type Styles = VariantProps<typeof toggleStyles>;

/** Variants that read well when the selected state is filled with the primary color. */
export type ToggleVariant = Extract<
  NonNullable<Styles["variant"]>,
  "outline" | "ghost" | "secondary"
>;

export interface ToggleProps extends ToggleButtonProps {
  /** Look of the toggle. Defaults to the enclosing group's variant, or `outline`. */
  variant?: ToggleVariant;
  /** Size of the toggle. Defaults to the enclosing group's size, or `md`. */
  size?: Styles["size"];
  /** Square toggle for an icon on its own. Give it an `aria-label`. */
  isIcon?: boolean;
}

/**
 * A button that stays on or off. Looks like a Button, and the "on" state is
 * filled with the primary color. Built on react-aria's ToggleButton, so press,
 * focus and `aria-pressed` are handled for you. It reads the defaults of a
 * ButtonGroup or ToggleGroup around it.
 *
 * `children` can be a function of `{ isSelected }` to change the content with
 * the state.
 *
 * @example
 * <Toggle aria-label="Bookmark" onChange={setBookmarked}>
 *   <BookmarkIcon />
 * </Toggle>
 */
export function Toggle({
  variant,
  size,
  isIcon,
  className,
  ...props
}: ToggleProps) {
  const group = useButtonGroup();

  return (
    <ToggleButton
      {...props}
      // A group or a toolbar that is disabled disables its toggles too.
      isDisabled={props.isDisabled ?? group?.isDisabled}
      className={cx(
        toggleStyles({
          variant: variant ?? (group?.variant as ToggleVariant | undefined),
          size: size ?? group?.size,
          isIcon,
        }),
        className,
      )}
    />
  );
}

2. Add the context Toggle reads (skip if you installed ButtonGroup)

It lets a Toggle pick up the variant and size of a surrounding group.

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

/** Defaults a ButtonGroup passes down to the buttons inside it. */
export type ButtonGroupContextValue = Pick<
  VariantProps<typeof buttonStyles>,
  "variant" | "size"
> & {
  isDisabled?: boolean;
};

const ButtonGroupContext = createContext<ButtonGroupContextValue | null>(null);

export const ButtonGroupProvider = ButtonGroupContext.Provider;

/** The enclosing ButtonGroup's defaults, or null outside of one. */
export function useButtonGroup() {
  return useContext(ButtonGroupContext);
}

3. Use it

import { Toggle } from "@/components/ui/toggle/toggle";

Anatomy

A toggle is one button with an icon, a label, or both.

<Toggle onChange={setSaved}>
  <BookmarkIcon />  {/* icon: optional */}
  Bookmark          {/* label */}
</Toggle>
<button aria-pressed="false">Bookmark</button>              <!-- off -->
<button aria-pressed="true" data-selected>Bookmark</button>  <!-- on, filled -->
PartRendered asNotes
Togglebutton with aria-pressedFlips between off and on each time it is pressed. The on state is filled with the primary color.
Iconsvg childOptional. Sized and spaced automatically by size.
Labeltext childOptional. Leave it out and set isIcon for an icon-only toggle.

A toggle with only an icon has no text for a screen reader, so give it an aria-label.

Examples

Live previews with code you can copy.

Usage

Not bookmarked

Default selected

Start in the on state without controlling it.

Controlled

Keep the state yourself with isSelected and onChange.

isSelected: true

Render props

Pass a function as children to change the content with the state.

Icon only

A square toggle with only an icon. Always add an aria-label.

Variants

Sizes

Disabled

In a button group

A Toggle joins a ButtonGroup like any Button and takes the group's variant and size.

Component API

Toggle accepts every prop of the react-aria-components ToggleButton, plus the ones below.

PropTypeDefault
isSelectedboolean-
defaultSelectedbooleanfalse
onChange(isSelected: boolean) => void-
childrenReactNode | (({ isSelected }) => ReactNode)-
variant"outline" | "secondary" | "ghost""outline"
size"xxs" | "xs" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "4xl" | "icon""md"
isIconbooleanfalse
isDisabledbooleanfalse
aria-labelstring-
classNamestring | (renderProps) => string-