← Components

Actions · Material 3: Segmented buttons

Segmented control

Choose one option (or several) from a small set. The selected pill slides and stretches between options.

Examples and variants

Single choice

Switch views or sort order.

Example
function SegmentedSingle() {
  return (
    <ToggleGroup defaultValue={["list"]} aria-label="View">
      <ToggleGroupItem value="list">List</ToggleGroupItem>
      <ToggleGroupItem value="grid">Grid</ToggleGroupItem>
      <ToggleGroupItem value="board">Board</ToggleGroupItem>
    </ToggleGroup>
  )
}

Multiple

Independent toggles in one group, like text styles.

Example
function SegmentedMultiple() {
  return (
    <ToggleGroup multiple defaultValue={["bold"]} aria-label="Text style">
      <ToggleGroupItem value="bold" aria-label="Bold">
        <BoldIcon />
      </ToggleGroupItem>
      <ToggleGroupItem value="italic" aria-label="Italic">
        <ItalicIcon />
      </ToggleGroupItem>
      <ToggleGroupItem value="underline" aria-label="Underline">
        <UnderlineIcon />
      </ToggleGroupItem>
    </ToggleGroup>
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/toggle-group.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install @base-ui/react class-variance-authority cn
  2. Copy these 2 files to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/toggle.tsxtoggle
      components/ui/toggle.tsx
      "use client"
      
      import * as React from "react"
      import { Toggle as TogglePrimitive } from "@base-ui/react/toggle"
      import { cva, type VariantProps } from "class-variance-authority"
      import { cn } from "cn"
      
      const toggleVariants = cva(
        "group/toggle relative inline-flex items-center justify-center gap-1 overflow-visible rounded-(--button-corner) border-0 text-sm font-medium whitespace-nowrap outline-none transition-colors duration-(--duration-fast) ease-(--ease-out) text-(--toggle-label) hover:bg-(--toggle-container-hover) active:bg-(--toggle-container-pressed) focus-visible:shadow-(--focus-ring) disabled:pointer-events-none disabled:text-(--toggle-label-disabled) data-pressed:text-(--toggle-label) [&_svg]:pointer-events-none [&_svg]:relative [&_svg]:z-[1] [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-icon-md",
        {
          variants: {
            variant: {
              default: "bg-transparent",
              outline:
                "bg-(--toggle-outline-container) shadow-1 hover:bg-(--toggle-outline-container-hover)",
            },
            size: {
              default: "h-control-md min-w-control-md px-3",
              sm: "h-control-sm min-w-control-sm px-2.5 [&_svg:not([class*='size-'])]:size-icon-sm",
              lg: "h-control-lg min-w-control-lg px-4",
            },
          },
          defaultVariants: {
            variant: "default",
            size: "default",
          },
        }
      )
      
      function Toggle({
        className,
        variant = "default",
        size = "default",
        burst = false,
        onPointerDown,
        onPressedChange,
        children,
        ...props
      }: TogglePrimitive.Props &
        VariantProps<typeof toggleVariants> & {
          /** Turning on pops a ring of dots (likes, favourites). */
          burst?: boolean
        }) {
        const [burstId, setBurstId] = React.useState(0)
        function handlePointerDown(event: Parameters<NonNullable<TogglePrimitive.Props["onPointerDown"]>>[0]) {
          onPointerDown?.(event)
          const rect = event.currentTarget.getBoundingClientRect()
          event.currentTarget.style.setProperty("--press-x", `${event.clientX - rect.left}px`)
          event.currentTarget.style.setProperty("--press-y", `${event.clientY - rect.top}px`)
        }
      
        return (
          <TogglePrimitive
            data-slot="toggle"
            className={cn(toggleVariants({ variant, size, className }))}
            {...props}
            onPointerDown={handlePointerDown}
            onPressedChange={(pressed, details) => {
              if (burst && pressed) setBurstId((n) => n + 1)
              onPressedChange?.(pressed, details)
            }}
          >
            <span key={burst ? `icon-${burstId}` : "icon"} className={cn("relative z-[1] inline-flex items-center justify-center gap-[inherit]", burst && burstId > 0 && "toggle-burst-icon")}>
              {children}
            </span>
            {burst && burstId > 0 ? (
              <span key={`burst-${burstId}`} aria-hidden className="toggle-burst pointer-events-none absolute inset-0 z-[2]">
                {Array.from({ length: 8 }, (_, i) => (
                  <span key={i} className="toggle-burst-dot absolute top-1/2 left-1/2 size-1.5 rounded-full" style={{ "--angle": `${i * 45}deg` } as React.CSSProperties} />
                ))}
              </span>
            ) : null}
          </TogglePrimitive>
        )
      }
      
      export { Toggle, toggleVariants }
      
    • components/ui/toggle-group.tsxtoggle-group
      components/ui/toggle-group.tsx
      "use client"
      
      import { useCallback, useLayoutEffect, useRef, useState } 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 { useLiquidIndicator } from "@/hooks/use-liquid-indicator"
      import { useMotionLevel } from "@/lib/motion/use-motion-level"
      import { toggleVariants } from "@/components/ui/toggle"
      
      function ToggleGroup({
        className,
        variant,
        size,
        orientation = "horizontal",
        children,
        ...props
      }: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
        const listRef = useRef<HTMLDivElement>(null)
        const { level, ref: motionRef } = useMotionLevel<HTMLDivElement>()
        // Stable merged ref: an inline one re-attaches every render and loops through useMotionLevel's state.
        const setRefs = useCallback(
          (node: HTMLDivElement | null) => {
            listRef.current = node
            motionRef(node)
          },
          [motionRef]
        )
        const [active, setActive] = useState(0)
        const [single, setSingle] = useState(true)
        const indicator = useLiquidIndicator(listRef, active, {
          stretch: level === "liquid",
        })
      
        useLayoutEffect(() => {
          const root = listRef.current
          if (!root) return
      
          const read = () => {
            const items = [...root.querySelectorAll<HTMLElement>("[data-slot=toggle-group-item]")]
            const pressed = items.filter((item) => item.hasAttribute("data-pressed"))
            setSingle(pressed.length === 1)
            const index = items.indexOf(pressed[0])
            if (index >= 0) setActive(index)
          }
      
          read()
          const observer = new MutationObserver(read)
          observer.observe(root, {
            subtree: true,
            attributes: true,
            attributeFilter: ["data-pressed"],
          })
          return () => observer.disconnect()
        }, [])
      
        return (
          <ToggleGroupPrimitive
            data-slot="toggle-group"
            data-variant={variant}
            data-size={size}
            data-orientation={orientation}
            orientation={orientation}
            data-multiple={single ? undefined : ""}
            className={cn(
              "relative inline-flex w-fit items-center gap-inline-xs rounded-(--segmented-corner) bg-(--segmented-container) p-(--segmented-padding)",
              "data-vertical:flex-col data-vertical:items-stretch",
              className
            )}
            {...props}
            ref={setRefs}
          >
            {single ? (
              <span
                aria-hidden
                className="absolute rounded-(--segmented-corner) bg-(--segmented-indicator) shadow-(--segmented-indicator-elevation)"
                style={{
                  ...indicator.style,
                  top: "var(--space-gap-inline-xs)",
                  bottom: "var(--space-gap-inline-xs)",
                  transition: level === "still" ? "none" : indicator.style.transition,
                }}
              />
            ) : null}
            {children}
          </ToggleGroupPrimitive>
        )
      }
      
      function ToggleGroupItem({
        className,
        children,
        variant = "default",
        size = "default",
        ...props
      }: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
        return (
          <TogglePrimitive
            data-slot="toggle-group-item"
            data-liquid-item
            data-variant={variant}
            data-size={size}
            className={cn(
              toggleVariants({ variant, size }),
              "relative z-[1] bg-transparent shadow-none hover:bg-transparent data-pressed:bg-transparent",
              className
            )}
            {...props}
          >
            {children}
          </TogglePrimitive>
        )
      }
      
      export { ToggleGroup, ToggleGroupItem }
      

Imports

What the examples on this page import:

Imports
import { BoldIcon, ItalicIcon, UnderlineIcon } from "lucide-react"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"

Anatomy

  1. 1Container · --segmented-container, --segmented-corner, --segmented-padding.
  2. 2Indicator · The sliding pill: --segmented-indicator with --segmented-indicator-elevation.
  3. 3Item · Label or icon. Pressed items turn medium weight.

Props

PropTypeDefaultDescription
defaultValue / valuestring[]—Selected values.
multiplebooleanfalseAllow several pressed items.
onValueChange(value: string[]) => void—Called on change.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--segmented-heightvar(--size-control-md)40pxsame
--segmented-containervar(--surface-container)oklch(0.965 0.005 95)oklch(0.12 0 0)
--segmented-indicatorvar(--surface-container-lowest)oklch(1 0 0)oklch(0.14 0 0)
--segmented-indicator-elevationvar(--elevation-1)0 1px 1px -0.5px oklch(0.22 0.01 260 / 7%), 0 2px 3px -1px oklch(0.22 0.01 260 / 10%), 0 4px 8px -4px oklch(0.22 0.01 260 / 6%)0 1px 2px oklch(0 0 0 / 35%), 0 2px 10px oklch(0 0 0 / 25%)
--segmented-cornervar(--shape-full)999pxsame
--segmented-paddingvar(--space-gap-inline-xs)4pxsame

Motion

TriggerWhat happensTokens
SelectThe pill stretches toward the new item, then catches up.--duration-fast, --duration-medium

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • Arrow keys move between items; Space or Enter presses.
  • Give the group an aria-label.
  • Icon items need aria-label.

Usage

Do

  • 2 to 5 short options.

Don’t

  • Don't use for navigation between pages (use Tabs or Navigation).

Code

components/ui/toggle-group.tsx
"use client"

import { useCallback, useLayoutEffect, useRef, useState } 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 { useLiquidIndicator } from "@/hooks/use-liquid-indicator"
import { useMotionLevel } from "@/lib/motion/use-motion-level"
import { toggleVariants } from "@/components/ui/toggle"

function ToggleGroup({
  className,
  variant,
  size,
  orientation = "horizontal",
  children,
  ...props
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
  const listRef = useRef<HTMLDivElement>(null)
  const { level, ref: motionRef } = useMotionLevel<HTMLDivElement>()
  // Stable merged ref: an inline one re-attaches every render and loops through useMotionLevel's state.
  const setRefs = useCallback(
    (node: HTMLDivElement | null) => {
      listRef.current = node
      motionRef(node)
    },
    [motionRef]
  )
  const [active, setActive] = useState(0)
  const [single, setSingle] = useState(true)
  const indicator = useLiquidIndicator(listRef, active, {
    stretch: level === "liquid",
  })

  useLayoutEffect(() => {
    const root = listRef.current
    if (!root) return

    const read = () => {
      const items = [...root.querySelectorAll<HTMLElement>("[data-slot=toggle-group-item]")]
      const pressed = items.filter((item) => item.hasAttribute("data-pressed"))
      setSingle(pressed.length === 1)
      const index = items.indexOf(pressed[0])
      if (index >= 0) setActive(index)
    }

    read()
    const observer = new MutationObserver(read)
    observer.observe(root, {
      subtree: true,
      attributes: true,
      attributeFilter: ["data-pressed"],
    })
    return () => observer.disconnect()
  }, [])

  return (
    <ToggleGroupPrimitive
      data-slot="toggle-group"
      data-variant={variant}
      data-size={size}
      data-orientation={orientation}
      orientation={orientation}
      data-multiple={single ? undefined : ""}
      className={cn(
        "relative inline-flex w-fit items-center gap-inline-xs rounded-(--segmented-corner) bg-(--segmented-container) p-(--segmented-padding)",
        "data-vertical:flex-col data-vertical:items-stretch",
        className
      )}
      {...props}
      ref={setRefs}
    >
      {single ? (
        <span
          aria-hidden
          className="absolute rounded-(--segmented-corner) bg-(--segmented-indicator) shadow-(--segmented-indicator-elevation)"
          style={{
            ...indicator.style,
            top: "var(--space-gap-inline-xs)",
            bottom: "var(--space-gap-inline-xs)",
            transition: level === "still" ? "none" : indicator.style.transition,
          }}
        />
      ) : null}
      {children}
    </ToggleGroupPrimitive>
  )
}

function ToggleGroupItem({
  className,
  children,
  variant = "default",
  size = "default",
  ...props
}: TogglePrimitive.Props & VariantProps<typeof toggleVariants>) {
  return (
    <TogglePrimitive
      data-slot="toggle-group-item"
      data-liquid-item
      data-variant={variant}
      data-size={size}
      className={cn(
        toggleVariants({ variant, size }),
        "relative z-[1] bg-transparent shadow-none hover:bg-transparent data-pressed:bg-transparent",
        className
      )}
      {...props}
    >
      {children}
    </TogglePrimitive>
  )
}

export { ToggleGroup, ToggleGroupItem }