ComponentsToggle Group

Toggle Group

Group of toggles on Base UI that share variant and size through context. Set spacing to zero to join the items into one segmented control, laid out horizontally or vertically.

"use client"

import * as React from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { type VariantProps } from "class-variance-authority"
import { cn } from "cn"

import { toggleVariants } from "@/components/ui/toggle"

const ToggleGroupContext = React.createContext<
  VariantProps<typeof toggleVariants> & {
    spacing?: number
    orientation?: "horizontal" | "vertical"
  }
>({
  size: "default",
  variant: "default",
  spacing: 2,
  orientation: "horizontal",
})

function ToggleGroup({
  className,
  variant,
  size,
  spacing = 2,
  orientation = "horizontal",
  children,
  ...props
}: ToggleGroupPrimitive.Props &
  VariantProps<typeof toggleVariants> & {
    spacing?: number
    orientation?: "horizontal" | "vertical"
  }) {
  return (
    <ToggleGroupPrimitive
      data-slot="toggle-group"
      data-variant={variant}
      data-size={size}
      data-spacing={spacing}
      data-orientation={orientation}
      style={{ "--gap": spacing } as React.CSSProperties}
      className={cn(
        "group/toggle-group flex w-fit flex-row items-center gap-[--spacing(var(--gap))] data-[spacing=0]:data-[variant=outline]:rounded-3xl data-vertical:flex-col data-vertical:items-stretch",
        className
      )}
      {...props}
    >
      <ToggleGroupContext.Provider
        value={{ variant, size, spacing, orientation }}
      >
        {children}
      </ToggleGroupContext.Provider>
    </ToggleGroupPrimitive>
  )
}

function ToggleGroupItem({
  className,
  children,
  variant = "default",
  size = "default",
  ...props
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
  const context = React.useContext(ToggleGroupContext)

  return (
    <TogglePrimitive
      data-slot="toggle-group-item"
      data-variant={context.variant || variant}
      data-size={context.size || size}
      data-spacing={context.spacing}
      className={cn(
        "shrink-0 group-data-[spacing=0]/toggle-group:rounded-none group-data-[spacing=0]/toggle-group:px-3 group-data-[spacing=0]/toggle-group:shadow-none focus:z-10 focus-visible:z-10 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-end]:pr-2.5 group-data-[spacing=0]/toggle-group:has-data-[icon=inline-start]:pl-2.5 group-data-horizontal/toggle-group:data-[spacing=0]:first:rounded-l-3xl group-data-vertical/toggle-group:data-[spacing=0]:first:rounded-t-3xl group-data-horizontal/toggle-group:data-[spacing=0]:last:rounded-r-3xl group-data-vertical/toggle-group:data-[spacing=0]:last:rounded-b-3xl data-[state=on]:bg-muted group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:border-l-0 group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:border-t-0 group-data-horizontal/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-l group-data-vertical/toggle-group:data-[spacing=0]:data-[variant=outline]:first:border-t",
        toggleVariants({
          variant: context.variant || variant,
          size: context.size || size,
        }),
        className
      )}
      {...props}
    >
      {children}
    </TogglePrimitive>
  )
}

export { ToggleGroup, ToggleGroupItem }

Installation

pnpm dlx shadcn add @01orbital/toggle-group
npx shadcn add @01orbital/toggle-group
yarn shadcn add @01orbital/toggle-group
bunx --bun shadcn add @01orbital/toggle-group

Add the @01orbital registry to components.json once (install guide), then run the command.

It lands at components/ui/toggle-group.tsx, as source you own and edit.

Toggle Group components

The library's own toggle group components, each installed on its own.

01

segmented-control

Component 01 · segmented-control

Segmented Control

Pill segmented control on Base UI ToggleGroup: a muted track where a lifted card-ground thumb glides to the pressed item, still under reduced motion. Horizontal only; values are arrays, as in Base UI. Open its docs page

pnpm dlx shadcn add @01orbital/segmented-control
npx shadcn add @01orbital/segmented-control
yarn shadcn add @01orbital/segmented-control
bunx --bun shadcn add @01orbital/segmented-control
"use client"

import { createContext, useContext, useId, useMemo, useState } from "react"
import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group"
import { cn } from "cn"
import { LayoutGroup, motion, useReducedMotion } from "motion/react"

// value/onValueChange/defaultValue take arrays, per Base UI ToggleGroup.
// className is a string here, not Base UI's state callback: the styling is
// the kit's, and state comes through data-pressed and data-disabled.
type Styled<P> = Omit<P, "className"> & {
  /**
   * Extra classes, as a string only: Base UI's function form is not
   * accepted. On `SegmentedControl` they land on the track, and on
   * `SegmentedControlItem` on the toggle button.
   */
  className?: string
}

// The group keeps the pressed values so each item knows whether it holds the
// thumb; a controlled value wins over the inner state.
const PressedContext = createContext<{
  pressed: Set<string>
  group: string
  multiple: boolean
}>({ pressed: new Set(), group: "", multiple: false })

/**
 * A row of toggle buttons on a rounded track. The pressed one sits on a
 * raised thumb that slides over from the last one pressed. Put
 * `SegmentedControlItem` parts inside.
 *
 * It is Base UI's `ToggleGroup`, so `value`, `defaultValue` and
 * `onValueChange` use arrays of item values. Without `multiple`, one item is
 * always on: pressing the active item again does nothing, and
 * `onValueChange` is not called with an empty array. With `multiple`, every
 * item can be turned off. It is horizontal only, and `className` takes a
 * string.
 */
function SegmentedControl({
  className,
  value,
  defaultValue,
  onValueChange,
  multiple = false,
  ...props
}: Styled<Omit<ToggleGroupPrimitive.Props, "orientation">>) {
  const group = useId()
  const [inner, setInner] = useState<string[]>(
    (defaultValue as string[] | undefined) ?? []
  )
  const current = (value as string[] | undefined) ?? inner
  const key = current.join("\u0000")
  const context = useMemo(
    () => ({
      pressed: new Set(key ? key.split("\u0000") : []),
      group,
      multiple,
    }),
    [key, group, multiple]
  )
  return (
    <PressedContext.Provider value={context}>
      <LayoutGroup id={group}>
        <ToggleGroupPrimitive
          data-slot="segmented-control"
          value={current}
          multiple={multiple}
          onValueChange={(next, event) => {
            // One stays on: a press on the active item is ignored.
            if (!multiple && next.length === 0) {
              event.cancel()
              return
            }
            // The consumer goes first: event.cancel() keeps the old value.
            onValueChange?.(next, event)
            if (!event.isCanceled) setInner(next as string[])
          }}
          className={cn(
            // The track: a muted well; in dark a faint lit rim on its top edge.
            "inline-flex items-center gap-1 rounded-full bg-muted p-1 ring-1 ring-border",
            "dark:bg-foreground/6 dark:shadow-[inset_0_1px_0_rgba(255,255,255,0.05)] dark:ring-foreground/10",
            className
          )}
          {...props}
        />
      </LayoutGroup>
    </PressedContext.Provider>
  )
}

/**
 * One option in a `SegmentedControl`, built on Base UI's `Toggle`. Give it a
 * string `value`. It is square for one character or an icon and widens to
 * fit a word.
 *
 * The pressed item sits on the thumb, a card-colored pill with a soft shadow
 * (a light wash in dark mode) that glides over from the last item pressed;
 * reduced motion moves it at once. The other items stay muted and come up
 * to full ink on hover. When the control has `multiple`, each pressed item
 * gets its own thumb, without the glide.
 */
function SegmentedControlItem({
  className,
  children,
  value,
  ...props
}: Styled<TogglePrimitive.Props>) {
  const { pressed, multiple } = useContext(PressedContext)
  const reduce = useReducedMotion()
  const on = typeof value === "string" && pressed.has(value)
  return (
    <TogglePrimitive
      data-slot="segmented-control-item"
      value={value}
      className={cn(
        "relative isolate flex h-8 min-w-8 items-center justify-center rounded-full px-2.5 text-sm font-medium text-muted-foreground tabular-nums",
        "transition-colors duration-150 ease-out motion-reduce:transition-none",
        "hover:text-foreground",
        "focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none",
        "data-disabled:pointer-events-none data-disabled:opacity-50",
        "data-pressed:text-foreground",
        className
      )}
      {...props}
    >
      {/* The thumb: one shared element per group, so it glides to whichever
          item is pressed instead of popping. With several pressed at once
          each keeps its own, still. */}
      {on && (
        <motion.span
          aria-hidden="true"
          layoutId={multiple ? undefined : "thumb"}
          transition={
            reduce
              ? { duration: 0 }
              : { type: "spring", stiffness: 520, damping: 42, mass: 0.8 }
          }
          className="absolute inset-0 -z-10 rounded-full bg-card shadow-xs dark:bg-foreground/15"
        />
      )}
      {children}
    </TogglePrimitive>
  )
}

export { SegmentedControl, SegmentedControlItem }

Dependencies

npm: @base-ui/react, class-variance-authority, cn. The CLI installs them for you.

Registry pieces it installs with it:

  • toggle