Segmented Control

Picks one of a few options from a row of buttons, with an indicator that slides to the choice.

It works like a radio group: one value and a single tab stop, with the arrow keys moving between items. Name it with aria-label, or put it in a Field whose label names it. The docs site’s own theme and mode switchers are segmented controls.

Preview
basic.tsx
import { SegmentedControl, SegmentedControlItem } from "~/components/ui/segmented-control"

export default function Example() {
  return (
    <SegmentedControl aria-label="View" defaultValue="list">
      <SegmentedControlItem value="list">List</SegmentedControlItem>
      <SegmentedControlItem value="grid">Grid</SegmentedControlItem>
      <SegmentedControlItem value="board">Board</SegmentedControlItem>
    </SegmentedControl>
  )
}

Sizes and disabled items

size="sm" suits toolbars. A disabled item is skipped by the arrow keys.

Preview
sizes.tsx
import { SegmentedControl, SegmentedControlItem } from "~/components/ui/segmented-control"

export default function Example() {
  return (
    <div className="grid justify-items-center gap-lg">
      <SegmentedControl aria-label="Density" size="sm" defaultValue="comfortable">
        <SegmentedControlItem value="compact">Compact</SegmentedControlItem>
        <SegmentedControlItem value="comfortable">Comfortable</SegmentedControlItem>
        <SegmentedControlItem value="spacious" disabled>
          Spacious
        </SegmentedControlItem>
      </SegmentedControl>
      <SegmentedControl aria-label="Billing period" defaultValue="monthly">
        <SegmentedControlItem value="monthly">Monthly</SegmentedControlItem>
        <SegmentedControlItem value="yearly">Yearly</SegmentedControlItem>
      </SegmentedControl>
    </div>
  )
}

Dependencies

What it's built from and what's built from it in Mocha, 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.20

Installation

Set the project up for Mocha 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/mocha/segmented-control.json

Manually

Install its packages:

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

Add the components it uses first, listed under Dependencies.

Then copy the source:

components/ui/segmented-control.tsx
import {
  SegmentedControl as SegmentedControlPrimitive,
  SegmentedControlIndicator as SegmentedControlIndicatorPrimitive,
  SegmentedControlItem as SegmentedControlItemPrimitive,
} from "@ui-sdk/react/segmented-control"
import type * as React from "react"

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

type SegmentedControlProps<T extends string> = React.ComponentProps<
  typeof SegmentedControlPrimitive<T>
> & {
  /** Height of the items. Their text is small and bold at either size, like a button's. */
  size?: "sm" | "md"
}

/**
 * Picks one of a few options from a row of buttons, with an indicator that
 * slides to the choice. The indicator is built in. Name the control with
 * `aria-label`, or put it in a `Field` whose label names it.
 */
function SegmentedControl<T extends string = string>({
  size = "md",
  className,
  children,
  ...props
}: SegmentedControlProps<T>) {
  return (
    <SegmentedControlPrimitive<T>
      data-size={size}
      className={cnState(
        [
          // Items are buttons, which inherit the control's font.
          textVariants({ size: "xs", tone: "muted" }),
          "group/segmented relative isolate inline-flex w-fit items-center gap-3xs rounded-lg bg-muted p-3xs",
          "data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch",
          "data-disabled:opacity-50",
        ].join(" "),
        className,
      )}
      {...props}
    >
      {(state) => (
        <>
          <SegmentedControlIndicator />
          {typeof children === "function" ? children(state) : children}
        </>
      )}
    </SegmentedControlPrimitive>
  )
}

/** One option. Its `value` becomes the control's value when it's checked. */
function SegmentedControlItem({
  className,
  ...props
}: React.ComponentProps<typeof SegmentedControlItemPrimitive>) {
  return (
    <SegmentedControlItemPrimitive
      className={cnState(
        [
          textVariants({ weight: "bold" }),
          "relative inline-flex cursor-pointer items-center justify-center gap-xs rounded-md px-md whitespace-nowrap",
          "h-8 group-data-[size=sm]/segmented:h-6 group-data-[size=sm]/segmented:px-sm",
          "transition-colors duration-150 hover:text-foreground data-checked:text-foreground",
          "outline-none focus-visible:ring-4 focus-visible:ring-ring",
          "data-disabled:cursor-not-allowed data-disabled:opacity-50 data-disabled:hover:text-muted-foreground",
          "[&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
        ].join(" "),
        className,
      )}
      {...props}
    />
  )
}

/** The sliding background behind the checked item. `SegmentedControl` renders one for you. */
function SegmentedControlIndicator({
  className,
  ...props
}: React.ComponentProps<typeof SegmentedControlIndicatorPrimitive>) {
  return (
    <SegmentedControlIndicatorPrimitive
      aria-hidden="true"
      className={cnState(
        [
          "absolute -z-10 rounded-md bg-background shadow-sm",
          "top-(--segmented-control-indicator-top) left-(--segmented-control-indicator-left) h-(--segmented-control-indicator-height) w-(--segmented-control-indicator-width)",
          "invisible data-visible:visible",
          "transition-[left,top,width,height] duration-200 ease-out motion-reduce:transition-none",
        ].join(" "),
        className,
      )}
      {...props}
    />
  )
}

export { SegmentedControl, SegmentedControlIndicator, SegmentedControlItem }
export type { SegmentedControlProps }

API reference

Generated from Mocha'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.

SegmentedControl

Picks one of a few options from a row of buttons, with an indicator that slides to the choice. The indicator is built in. Name the control with aria-label, or put it in a Field whose label names it.

sizeours

Height of the items. Their text is small and bold at either size, like a button's.

Type "sm" | "md" · Default md

children

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

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

className

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

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

controller

Checks items from anywhere. Create one with createSegmentedControlController().

Type { getValue: () => T | null; setValue: (value: T | null, details?: SegmentedControlChangeOptions) => boolean; focus: () => void; }

debug

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

Type boolean

defaultValue

The item checked at first, when uncontrolled. A form reset returns to it.

Type string | null

disabled

Disables every item: they can't be focused or changed, and the value isn't submitted.

Type boolean

form

The id of a form to belong to, when the segmented control isn't inside that form.

Type string

loop

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

Type boolean · Default true

name

The name the value submits under. Without one, the segmented control submits nothing.

Type string

onValueChange

Runs when a user or a form reset wants to change the value. details.reason says why, and details.cancel() stops it.

Type (value: T | null, details: ChangeDetails<SegmentedControlValueChangeReason>) => void

orientation

Which way the items run, for styling and for screen readers. Arrow keys on both axes move between items either way, as in any radio group.

Type SegmentedControlOrientation · Default "horizontal"

readOnly

Keeps the items focusable and the value submitted, but stops changes.

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<SegmentedControlState>

required

Blocks form submission until an item is checked, with the browser's own message.

Type boolean

style

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

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

value

The checked item's value. Pass it to control the segmented control. null checks nothing.

Type string | null

SegmentedControlIndicator

The sliding background behind the checked item. SegmentedControl renders one for you.

children

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

Type ReactNode | ((state: NoInfer<SegmentedControlIndicatorState>) => ReactNode)

className

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

Type string | ((state: NoInfer<SegmentedControlIndicatorState>) => string)

followHover

Whether it follows the item under the pointer, and goes back to the checked one when the pointer leaves the control.

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<NoInfer<SegmentedControlIndicatorState>>

style

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

Type CSSProperties | ((state: NoInfer<SegmentedControlIndicatorState>) => CSSProperties)

SegmentedControlItem

One option. Its value becomes the control's value when it's checked.

children

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

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

className

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

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

disabled

Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless focusableWhenDisabled is set.

Type boolean · Default false

render

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

Type RenderProp<SegmentedControlItemState>

style

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

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

value*

What the value becomes when this item is checked.

Type string