Toggle

A button that stays pressed, alone or in a group sharing one value.

A toggle reports its state with aria-pressed. In a ToggleGroup, each toggle has a value and the arrow keys move between them; multiple lets several stay pressed. Name icon-only toggles with aria-label.

Preview
basic.tsx
import { BookOpen, Columns2, Columns3, RectangleVertical } from "lucide-react"

import { Toggle, ToggleGroup } from "~/components/ui/toggle"

export default function Example() {
  return (
    <div className="flex flex-wrap items-center gap-xl">
      <Toggle aria-label="Show guides" defaultPressed>
        <Columns3 />
      </Toggle>
      <ToggleGroup aria-label="Pages shown" defaultValue={["spread"]}>
        <Toggle value="single" aria-label="Single page">
          <RectangleVertical />
        </Toggle>
        <Toggle value="spread" aria-label="Spread">
          <BookOpen />
        </Toggle>
        <Toggle value="columns" aria-label="Columns">
          <Columns2 />
        </Toggle>
      </ToggleGroup>
      <ToggleGroup aria-label="Text style" multiple>
        <Toggle variant="outline" value="bold">
          Bold
        </Toggle>
        <Toggle variant="outline" value="italic">
          Italic
        </Toggle>
      </ToggleGroup>
    </div>
  )
}

Dependencies

What it's built from and what's built from it in Base, read from the imports in its source.

UsesTextprimitive
Used byNothing yet.
Packages @ui-sdk/core@0.1.0-beta.20@ui-sdk/react@0.1.0-beta.20tailwind-variants@4.1.0

Installation

Set the project up for Base once first, as Getting started shows. Then add it with the CLI, or by hand.

With the CLI

terminal
npx shadcn@latest add https://design.zepez.dev/r/base/toggle.json

Manually

Install its packages:

terminal
npm install @ui-sdk/core@0.1.0-beta.20 @ui-sdk/react@0.1.0-beta.20 tailwind-variants@4.1.0

Add the components it uses first, listed under Dependencies.

Then copy the source:

components/ui/toggle.tsx
import {
  Toggle as TogglePrimitive,
  ToggleGroup as ToggleGroupPrimitive,
  ToggleIcon,
} from "@ui-sdk/react/toggle"
import type * as React from "react"
import { tv, type VariantProps } from "tailwind-variants"

import { textVariants } from "~/components/ui/text"
import { cnState } from "~/lib/utils"

const toggleVariants = tv({
  base: [
    textVariants({ size: "sm", weight: "medium" }),
    "inline-flex shrink-0 cursor-pointer items-center justify-center gap-2xs rounded-lg border border-transparent whitespace-nowrap text-foreground",
    "transition-colors duration-150 hover:bg-muted",
    "outline-none focus-visible:z-10 focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30",
    "data-pressed:bg-muted",
    "data-disabled:pointer-events-none data-disabled:opacity-50",
    "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
  ],
  variants: {
    variant: {
      ghost: "",
      outline: "border-border hover:bg-muted data-pressed:bg-muted",
    },
    size: {
      sm: "h-7 min-w-7 px-sm",
      md: "h-8 min-w-8 px-md",
      lg: "h-9 min-w-9 px-md",
    },
  },
  defaultVariants: { variant: "ghost", size: "md" },
})

type ToggleVariants = VariantProps<typeof toggleVariants>

type ToggleProps = React.ComponentProps<typeof TogglePrimitive> & {
  /** `outline` draws a border, for toggles that sit apart from a toolbar. */
  variant?: NonNullable<ToggleVariants["variant"]>
  /** Height and minimum width. */
  size?: NonNullable<ToggleVariants["size"]>
}

/** A button that stays pressed until pressed again, like Bold or a panel switch. Name icon-only toggles with `aria-label`. */
function Toggle({ variant, size, className, ...props }: ToggleProps) {
  return (
    <TogglePrimitive className={cnState(toggleVariants({ variant, size }), className)} {...props} />
  )
}

/**
 * Toggles sharing one value and arrow-key navigation. Give each toggle a
 * `value`, and the group an `aria-label`; `multiple` lets several stay pressed.
 */
function ToggleGroup({ className, ...props }: React.ComponentProps<typeof ToggleGroupPrimitive>) {
  return (
    <ToggleGroupPrimitive
      className={cnState(
        "flex w-fit items-center gap-2xs data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch",
        className,
      )}
      {...props}
    />
  )
}

export { Toggle, ToggleGroup, ToggleIcon, toggleVariants }
export type { ToggleProps }

API reference

Generated from Base's types. Props marked ours are added here; the rest come from the ui-sdk part it wraps. Every part also accepts its element's native attributes.

Toggle

A button that stays pressed until pressed again, like Bold or a panel switch. Name icon-only toggles with aria-label.

sizeours

Height and minimum width.

Type NonNullable<"sm" | "md" | "lg">

variantours

outline draws a border, for toggles that sit apart from a toolbar.

Type NonNullable<"outline" | "ghost">

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: ToggleState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: ToggleState) => string)

controller

Presses it from anywhere. Create one with createToggleController().

Type { isPressed: () => boolean; setPressed: (pressed: boolean, options?: ToggleChangeOptions) => boolean; toggle: (options?: ToggleChangeOptions) => boolean; focus: () => void; }

debug

Logs every state change with its reason to the console, in development builds.

Type boolean

defaultPressed

Whether it's pressed at first, when uncontrolled.

Type boolean · Default false

disabled

Stops presses. Alone, the toggle is natively disabled, unless focusableWhenDisabled is set. Inside a group or a toolbar, it stays focusable with aria-disabled, so arrow keys still reach it.

Type boolean · Default false

focusableWhenDisabled

Keeps a disabled toggle in the tab order with aria-disabled instead of the native attribute. Toggles in a group or a toolbar always are.

Type boolean · Default false

onPressedChange

Runs when a press wants to change it. details.reason says why, and details.cancel() stops it. Inside a group, it runs before the group's onValueChange, and canceling it cancels the group's change too.

Type (pressed: boolean, details: ChangeDetails<TogglePressedChangeReason>) => void

pressed

Whether it's pressed. Pass it to control the toggle. Inside a group, the group's value decides.

Type boolean

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<ToggleState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: ToggleState) => CSSProperties)

value

Identifies the toggle inside a group, whose value lists the pressed toggles' values. Defaults to a generated id.

Type string

ToggleGroup

Toggles sharing one value and arrow-key navigation. Give each toggle a value, and the group an aria-label; multiple lets several stay pressed.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: ToggleGroupState<string>) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: ToggleGroupState<string>) => string)

controller

Presses toggles from anywhere. Create one with createToggleGroupController().

Type { getValue: () => string[]; setValue: (value: string[], options?: ToggleGroupChangeOptions) => boolean; isPressed: (value: string) => boolean; toggle: (value: string, options?: ToggleGroupChangeOptions) => boolean; focus: (value?: string | undefined) => void; }

debug

Logs every state change with its reason to the console, in development builds.

Type boolean

defaultValue

The toggles pressed at first, when uncontrolled.

Type string[] · Default []

deselectable

Whether the pressed toggle can be unpressed when only one may be pressed. With false, one toggle stays pressed once any is. Ignored with multiple.

Type boolean · Default true

disabled

Stops every toggle from being pressed. They stay focusable with aria-disabled, so the group keeps its tab stop and stays discoverable.

Type boolean · Default false

loop

Whether arrow keys wrap from the last toggle to the first.

Type boolean · Default true

multiple

Whether several toggles can be pressed at once. Otherwise pressing one unpresses the others.

Type boolean · Default false

onValueChange

Runs when a toggle wants to be pressed or unpressed. details.reason says why, and details.cancel() stops it.

Type (value: string[], details: ChangeDetails<ToggleGroupValueChangeReason>) => void

orientation

Which arrow keys move between toggles: left and right, or up and down.

Type ToggleGroupOrientation · Default "horizontal"

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<ToggleGroupState<string>>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: ToggleGroupState<string>) => CSSProperties)

value

The pressed toggles' values. Pass it to control the group.

Type string[]