# Segmented control

Switch between views with an animated selection indicator.

Access: free. Category: Essentials. Kind: primitive.

## When to use

- Use it when a product interface needs switch between views with an animated selection indicator.
- Choose it when the host application can supply the required state and keep business logic outside the presentation component.

## Alternatives

- Choose tidal-button instead when press, loading, success and disabled states is the actual interface need, rather than segmented control.

## Setup for agents

Use React 19 and TypeScript. Initialize shadcn for your framework, then merge this exact entry into components.json:

```json
{
  "registries": {
    "@tidal-pro": {
      "url": "https://tidalui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${TIDALUI_TOKEN}"
      }
    }
  }
}
```

The namespace must be named **@tidal-pro** because transitive Pro dependencies use that namespace. Obtain an agent key from your active Pro account at https://tidalui.com/account. Keep TIDALUI_TOKEN in your local environment, never in components.json, client code, Git or logs.

```sh
export TIDALUI_TOKEN='your-private-agent-key'
npx shadcn@latest add @tidal-pro/waitlist-form
npx shadcn@latest add https://tidalui.com/r/tidal-button.json
```

Free command: `npx shadcn@latest add https://tidalui.com/r/<name>.json`.
Pro command: `npx shadcn@latest add @tidal-pro/<name>`.

Import the base stylesheet and every stylesheet listed on the installed item's metadata. For example:

```tsx
import "./components/ui/tidal.css";
import "./components/ui/hero-section.css";
// Place installed components inside this wrapper:
<div className="tidal-scope" data-theme="dark">...</div>
```

Omit data-theme for the default light theme. Put the attribute on the same tidal-scope element for dark mode. Every component installs the shared free tidal-base dependency. After upgrading, run `npx shadcn@latest add https://tidalui.com/r/tidal-base.json --overwrite` to receive current tokens. Review local modifications before overwriting.

Vite: Use React + TypeScript. Map @/* to ./src/* in paths and Vite resolve.alias. Import tidal.css and each component stylesheet in your application entry.

Next.js 15 App Router: Next.js App Router: import tidal.css and component CSS in app/layout.tsx. Interactive examples belong in a client component with "use client". Map @/* to ./* or ./src/* to match your project.

TypeScript 6: use paths without baseUrl:

```json
{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  }
}
```

Pro registry requests are server/CLI-only. Use the same-origin account interface in a browser; cross-origin Authorization preflights are intentionally unsupported.


## Install Segmented control

```sh
npx shadcn@latest add https://tidalui.com/r/segmented-control.json
```

Stylesheets: `components/ui/tidal.css`, `components/ui/segmented-control.css`.

## Minimal example

```tsx
import"./components/ui/tidal.css";
import"./components/ui/segmented-control.css";
import{TidalSegmentedControl}from"./components/ui/segmented-control";
export default()=><div className="tidal-scope"><TidalSegmentedControl label={"Demo"} onValueChange={() => {}} options={[{value:"value",label:"Demo"}]} value={"value"}/></div>;
```

## Structured props

- `TidalSegmentedControl.label: string`: Required label value accepted by this exported component.
- `TidalSegmentedControl.onValueChange: (value: string) => void`: Callback invoked when the value change interaction is proposed.
- `TidalSegmentedControl.options: Array<SegmentOption>`: Required options value accepted by this exported component.
- `TidalSegmentedControl.value: string`: Required value value accepted by this exported component.
- `TidalSegmentedControl.className?: string | undefined` (default ""): Optional class name value accepted by this exported component.

## Complete usage example

[Source](https://tidalui.com/examples/segmented-control.tsx) | [Manifest](https://tidalui.com/examples/segmented-control.json). Install the listed additional dependencies. Consumer fixture: TypeScript pass; Vite pass. This fixture check is distinct from the actual shadcn install receipt.

```tsx
import "./components/ui/tidal.css";

import { useState, useId, type PointerEvent } from "react";

import { TidalSegmentedControl } from "./components/ui/segmented-control";

import "./components/ui/segmented-control.css";



const tidalExampleStyles = ".segment-specimen{background:var(--t-surface);border:1px solid var(--t-border);border-radius:var(--t-radius-card);padding:21px;width:100%;max-width:315px;box-shadow:0 10px 20px -12px #00000026,0 1px 2px #00000008}.demo-eyebrow{font-size:11px;letter-spacing:1px;color:var(--t-muted);font-weight:500;margin:0 0 13px}.segment-stat{display:flex;align-items:center;justify-content:space-between;margin:20px 0 14px;gap:10px}.segment-stat strong{font-size:33px;font-weight:500;letter-spacing:-1.5px;line-height:1.1;font-variant-numeric:tabular-nums;animation:tidal-stat-in 220ms var(--t-ease-out)}.segment-stat>span{font-size:11px;padding:4px 7px;background:var(--t-wash);border-radius:5px;color:var(--t-accent)}.segment-bars{display:flex;align-items:flex-end;gap:7px;height:40px;margin-bottom:18px;overflow:hidden}.segment-bars span{flex:1;background:var(--t-border);border-radius:3px 3px 0 0;transition:height 320ms var(--t-ease-out)}.segment-bars span:nth-last-child(-n+3){background:var(--t-accent);opacity:.65}.segment-specimen .tidal-segments button{font-size:11px;padding:0 5px}\n\n@keyframes tidal-stat-in{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}\n.workspace-demo-sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}\n.segment-chart{position:relative;padding-top:26px}.segment-chart .segment-bars{height:60px;margin:0 0 18px;padding:6px 0;cursor:crosshair;touch-action:pan-y;min-height:44px}.segment-chart .segment-bars>span{flex:1;min-width:0;transition:height 420ms var(--t-ease-out),opacity 180ms,background 180ms}.segment-chart .segment-bars:has([data-selected=true])>span{opacity:.35}.segment-chart .segment-bars>span[data-selected=true]{opacity:1;background:var(--t-ink)}.segment-value{position:absolute;inset:0 0 auto;display:flex;align-items:center;justify-content:space-between;gap:12px;font-size:11px;color:var(--t-muted);pointer-events:none}.segment-value strong{color:var(--t-ink);font-weight:550;font-variant-numeric:tabular-nums}.segment-chart .segment-bars:focus-visible{outline-offset:3px}";

const segmentPeriods = {
  week: {
    total: 8240,
    growth: "+8.2%",
    weights: [26, 37, 29, 41, 46, 40, 56],
    labels: [
      "Mon, Oct 5",
      "Tue, Oct 6",
      "Wed, Oct 7",
      "Thu, Oct 8",
      "Fri, Oct 9",
      "Sat, Oct 10",
      "Sun, Oct 11",
    ],
  },
  month: {
    total: 32480,
    growth: "+14.8%",
    weights: [18, 25, 32, 23, 40, 36, 51, 64],
    labels: [
      "Oct 1–4",
      "Oct 5–8",
      "Oct 9–12",
      "Oct 13–16",
      "Oct 17–20",
      "Oct 21–24",
      "Oct 25–28",
      "Oct 29–31",
    ],
  },
  year: {
    total: 384920,
    growth: "+28.6%",
    weights: [14, 23, 26, 38, 33, 48, 62, 76, 65, 70, 73, 81],
    labels: [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ],
  },
};

export function SegmentDemo() {
  const [period, setPeriod] = useState<keyof typeof segmentPeriods>("month");
  const [inspected, setInspected] = useState<number | null>(null);
  const [focused, setFocused] = useState(false);
  const helpId = useId();
  const data = segmentPeriods[period];
  const weightTotal = data.weights.reduce((a, b) => a + b, 0);
  const values = data.weights.map((weight) =>
    Math.floor((weight / weightTotal) * data.total),
  );
  values[values.length - 1] += data.total - values.reduce((a, b) => a + b, 0);
  const active =
    inspected === null ? null : Math.min(inspected, values.length - 1);
  const money = (value: number) => "$" + value.toLocaleString("en-US");
  const selected = active ?? values.length - 1;
  function inspect(event: PointerEvent<HTMLDivElement>) {
    const bounds = event.currentTarget.getBoundingClientRect();
    setInspected(
      Math.max(
        0,
        Math.min(
          values.length - 1,
          Math.floor(
            ((event.clientX - bounds.left) / bounds.width) * values.length,
          ),
        ),
      ),
    );
  }
  return (
    <div className="segment-specimen">
      <p className="demo-eyebrow">REVENUE OVER TIME</p>
      <div className="segment-stat">
        <strong key={period}>{money(data.total)}</strong>
        <span>{data.growth}</span>
      </div>
      <div className="segment-chart">
        {active !== null ? (
          <div className="segment-value" aria-hidden="true">
            <span>{data.labels[active]}</span>
            <strong>{money(values[active])}</strong>
          </div>
        ) : null}
        <div
          className="segment-bars"
          role="slider"
          tabIndex={0}
          aria-label="Inspect revenue bars"
          aria-orientation="horizontal"
          aria-valuemin={0}
          aria-valuemax={values.length - 1}
          aria-valuenow={selected}
          aria-valuetext={`${data.labels[selected]}: ${money(values[selected])}`}
          aria-describedby={helpId}
          onPointerMove={(event) => {
            if (event.pointerType !== "touch") inspect(event);
          }}
          onPointerDown={(event) => {
            event.currentTarget.focus({ preventScroll: true });
            inspect(event);
          }}
          onPointerLeave={() => {
            if (!focused) setInspected(null);
          }}
          onFocus={() => {
            setFocused(true);
            setInspected((current) => current ?? values.length - 1);
          }}
          onBlur={() => {
            setFocused(false);
            setInspected(null);
          }}
          onKeyDown={(event) => {
            const step =
              event.key === "ArrowRight" || event.key === "ArrowUp"
                ? 1
                : event.key === "ArrowLeft" || event.key === "ArrowDown"
                  ? -1
                  : 0;
            if (!step && event.key !== "Home" && event.key !== "End") return;
            event.preventDefault();
            setInspected(
              event.key === "Home"
                ? 0
                : event.key === "End"
                  ? values.length - 1
                  : Math.max(0, Math.min(values.length - 1, selected + step)),
            );
          }}
        >
          {values.map((value, index) => (
            <span
              key={`${period}-${index}`}
              data-selected={active === index}
              data-label={data.labels[index]}
              data-value={value}
              aria-hidden="true"
              style={{ height: `${10 + (value / Math.max(...values)) * 38}px` }}
            />
          ))}
        </div>
      </div>
      <span id={helpId} className="workspace-demo-sr">
        Hover or tap a bar to inspect its revenue. Use arrow keys, Home or End
        when focused. Sample data.
      </span>
      <TidalSegmentedControl
        label="Revenue period"
        value={period}
        onValueChange={(value) => {
          setPeriod(value as keyof typeof segmentPeriods);
          setInspected(null);
        }}
        options={[
          { value: "week", label: "Week" },
          { value: "month", label: "Month" },
          { value: "year", label: "Year" },
        ]}
      />
    </div>
  );
}

export default function AgentExample() {
  return (
    <div className="tidal-scope" data-theme="light" dir="ltr">
      <style>{tidalExampleStyles}</style>
      <SegmentDemo />
    </div>
  );
}

```

## Gotchas

- Install the declared registry dependencies and render inside a tidal-scope with the foundation stylesheet loaded.

## Theme and accessibility

{"tokens":["--t-accent","--t-border","--t-border-strong","--t-canvas","--t-danger","--t-display","--t-ease-out","--t-ease-spring","--t-faint","--t-font","--t-ink","--t-line","--t-muted","--t-primary","--t-primary-contrast","--t-radius-card","--t-radius-control","--t-radius-overlay","--t-radius-panel","--t-ring","--t-shadow-lg","--t-shadow-soft","--t-soft","--t-subtle","--t-surface","--t-wash"],"darkMode":true}

{"keyboard":["Tab and Shift+Tab follow the component's native focus order.","Arrow-key behavior follows the exported composite-control implementation."],"aria":"The component wires labels and relationships from consumer-provided visible text or ARIA props; preserve those labels in production.","notes":"Verify focus visibility, text alternatives, contrast, and reduced motion in the final composition."}

Controlled: options ({value, label, disabled?}[]), value, onValueChange, label; optional className. Single-choice radio group. Arrow keys wrap enabled options; Home/End; disabled options skipped.
