Segmented
A pill switch for two to four choices, such as USD or INR.
Install
$ npx shadcn@latest add @nudgekit/segmentedOr with no config: npx shadcn@latest add https://ui.nudgekit.app/r/segmented.json
Usage
usage.tsx
import { Segmented } from "@/components/ui/segmented"
<Segmented
label="Currency"
options={[{ value: "USD", label: "USD" }, { value: "INR", label: "INR" }]}
value={currency}
onValueChange={setCurrency}
/>Do
- Use for two to four short choices.
- Always give it a label for screen readers.
Don't
- Use it for more than four options; use a select.
- Use it for navigation between pages.
Code
What the CLI writes into your project. It is yours to change.
components/ui/segmented.tsx
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
export interface SegmentedProps<T extends string> {
options: readonly { value: T; label: React.ReactNode }[];
value?: T;
defaultValue?: T;
onValueChange?: (value: T) => void;
/** Names the group for screen readers, for example "Billing currency". */
label: string;
className?: string;
}
/** A pill switch for two to four choices, such as Monthly or Annual, USD or INR. */
function Segmented<T extends string>({ options, value, defaultValue, onValueChange, label, className }: SegmentedProps<T>) {
const [inner, setInner] = React.useState<T>(defaultValue ?? options[0].value);
const current = value ?? inner;
return (
<div
role="radiogroup"
aria-label={label}
data-slot="segmented"
className={cn("inline-flex rounded-full border border-border bg-surface p-[3px]", className)}
>
{options.map((o) => {
const on = o.value === current;
return (
<button
key={o.value}
type="button"
role="radio"
aria-checked={on}
onClick={() => {
if (value === undefined) setInner(o.value);
onValueChange?.(o.value);
}}
className={cn(
"h-8 rounded-full px-3.5 text-[13px] transition-colors duration-150 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",
on ? "bg-background font-medium text-foreground ring-1 ring-border" : "text-muted-foreground hover:text-foreground",
)}
>
{o.label}
</button>
);
})}
</div>
);
}
export { Segmented };