Craft›Segmented Control

Segmented Control

An Apple-style segmented control: the selected pill slides to your pick on a spring and the labels settle under it; arrow keys, roving focus, icons (optionally with only the selected label shown), controlled or not, and a haptic tick on change.

Copy a ready prompt for Claude Code, Codex or Cursor

Seen on

Original to Copia

Dependencies

reacttailwindcssmotionlucide-react

Interaction type

keyboardspring

Install via CLI

pnpm dlx shadcn@latest add @copia/segmented-control

Without the namespace: npx shadcn@latest add https://copia-ui.vercel.app/r/segmented-control.json

How to use

demo.tsx
"use client"

import { LayoutGrid, List, Rows3 } from "lucide-react"
import { useEffect, useState } from "react"
import { SegmentedControl, type SegmentedControlProps } from "./segmented-control"

const VIEWS = [
  { value: "grid", label: "Grid", icon: <LayoutGrid /> },
  { value: "list", label: "List", icon: <List /> },
  { value: "rows", label: "Rows", icon: <Rows3 /> },
]
const PERIODS = ["Day", "Week", "Month", "Year"].map((p) => ({ value: p.toLowerCase(), label: p }))

/** Two controls that step through their options on their own until you touch one. */
export default function Demo({ size = "md", labels = "always" }: Pick<SegmentedControlProps, "size" | "labels">) {
  const [view, setView] = useState("grid")
  const [period, setPeriod] = useState("week")
  const [touched, setTouched] = useState(false)

  useEffect(() => {
    if (touched || matchMedia("(prefers-reduced-motion: reduce)").matches) return
    let step = 0
    const id = setInterval(() => {
      step++
      setPeriod(PERIODS[(step + 1) % PERIODS.length].value)
      if (step % 2 === 0) setView(VIEWS[(step / 2) % VIEWS.length].value)
    }, 900)
    return () => clearInterval(id)
  }, [touched])

  return (
    <div className="grid flex-1 place-items-center p-6" onPointerDown={() => setTouched(true)} onKeyDown={() => setTouched(true)}>
      <div className="flex flex-col items-center gap-5">
        <SegmentedControl label="Period" options={PERIODS} value={period} onValueChange={setPeriod} size={size} />
        <SegmentedControl label="View" options={VIEWS} value={view} onValueChange={setView} size={size} labels={labels} />
      </div>
    </div>
  )
}

Customization

Use the sliders button at the top right of the preview to tweak size, labels live and copy the generated JSX.

Props

PropTypeDefaultDescription
options{ value, label, icon? }[]-Segments in order.
value / defaultValue / onValueChangestring / string / (v) => voidfirst optionControlled or uncontrolled.
size"sm" | "md""md"Height and text size.
labelstring"Options"Accessible name of the group.
hapticsbooleantrueVibrate briefly on change, where supported.
labels"always" | "active""always""active" shows icons only and opens the selected option's label, its width animating with the pill.

Attribution

Original component, Apple (Human Interface Guidelines: Segmented controls). Recreated by Copia.

Read how it was reverse engineered

Source code

segmented-control.tsx
"use client"

import { AnimatePresence, LayoutGroup, motion, useReducedMotion } from "motion/react"
import { useId, useRef, useState } from "react"
import { cn } from "@/lib/utils"

export type SegmentedOption = { value: string; label: string; icon?: React.ReactNode }

export type SegmentedControlProps = {
  options: SegmentedOption[]
  value?: string
  defaultValue?: string
  onValueChange?: (value: string) => void
  /** Accessible name of the group. */
  label?: string
  size?: "sm" | "md"
  /** A short vibration when the selection changes, where supported. */
  haptics?: boolean
  /** "always" shows every label; "active" shows icons only and opens the selected one's label. Needs icons. */
  labels?: "always" | "active"
  className?: string
}

const SLIDE = { type: "spring", bounce: 0.2, duration: 0.45 } as const

/**
 * An Apple-style segmented control: the selected pill slides to the option
 * you pick and stretches a little on the way, the label underneath settles
 * into place. Arrow keys move the selection; it works controlled or not.
 */
export function SegmentedControl({ options, value, defaultValue, onValueChange, label = "Options", size = "md", haptics = true, labels = "always", className }: SegmentedControlProps) {
  const [internal, setInternal] = useState(defaultValue ?? options[0]?.value)
  const selected = value ?? internal
  const group = useId()
  const reduced = useReducedMotion()
  const buttons = useRef<(HTMLButtonElement | null)[]>([])

  const pick = (next: string) => {
    if (next === selected) return
    if (value === undefined) setInternal(next)
    onValueChange?.(next)
    if (haptics) navigator.vibrate?.(3)
  }

  const onKeyDown = (event: React.KeyboardEvent) => {
    const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]
    if (!step) return
    event.preventDefault()
    const at = options.findIndex((o) => o.value === selected)
    const next = (at + step + options.length) % options.length
    pick(options[next].value)
    buttons.current[next]?.focus()
  }

  return (
    <LayoutGroup id={group}>
      <div
        role="radiogroup"
        aria-label={label}
        onKeyDown={onKeyDown}
        className={cn("inline-flex items-center rounded-full bg-muted p-1", size === "sm" ? "text-xs" : "text-sm", className)}
      >
        {options.map((option, i) => {
          const active = option.value === selected
          const showLabel = labels === "always" || active || !option.icon
          return (
            <button
              key={option.value}
              ref={(el) => {
                buttons.current[i] = el
              }}
              type="button"
              role="radio"
              aria-checked={active}
              aria-label={showLabel ? undefined : option.label}
              title={showLabel ? undefined : option.label}
              tabIndex={active ? 0 : -1}
              onClick={() => pick(option.value)}
              className={cn(
                "relative flex items-center gap-1.5 rounded-full font-medium outline-none transition-colors duration-200 focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.97]",
                size === "sm" ? "h-7 px-3" : "h-9 px-4",
                active ? "text-foreground" : "text-muted-foreground hover:text-foreground",
              )}
            >
              {active && (
                <motion.span
                  layoutId="pill"
                  transition={reduced ? { duration: 0 } : SLIDE}
                  className="absolute inset-0 z-0 rounded-full bg-background shadow-[0_1px_2px_rgb(0_0_0/0.12),0_0_0_0.5px_rgb(0_0_0/0.06)]"
                />
              )}
              <span className="relative z-10 flex items-center">
                {option.icon && <span className="[&_svg]:size-4">{option.icon}</span>}
                {/* Copia: with labels="active" the label opens and closes, its width animating with the pill. */}
                <AnimatePresence initial={false}>
                  {showLabel && (
                    <motion.span
                      key="label"
                      initial={{ width: 0, opacity: 0, filter: "blur(4px)" }}
                      animate={{ width: "auto", opacity: 1, filter: "blur(0px)" }}
                      exit={{ width: 0, opacity: 0, filter: "blur(4px)" }}
                      transition={reduced ? { duration: 0 } : SLIDE}
                      className="overflow-hidden whitespace-nowrap"
                    >
                      <span className={option.icon ? "pl-1.5" : undefined}>{option.label}</span>
                    </motion.span>
                  )}
                </AnimatePresence>
              </span>
            </button>
          )
        })}
      </div>
    </LayoutGroup>
  )
}

Keep in mind

Most components here are recreations of the best interfaces out there. We don't claim to be the original creators: this is our attempt to reverse engineer, replicate and often add a few features. We credit everyone we can; if we missed someone, let us know.

Contact

Found a bug or a missing credit? Open an issue

License & usage

  • — Free to use and modify in personal and commercial projects (MIT).
  • — No attribution required, but a link back to Copia is appreciated.
  • — Demo images are not part of the license; replace them with your own.
PreviousNumber TickerNext Spine Accordion