Tabs
Animated React tabs built on shadcn/ui and Radix: the drop-in Tabs adds a line variant, vertical layout and panels that fade in — plus Motion blocks for tabs with a gliding active indicator and direction-aware panel transitions, and an iOS-style segmented control.
- Drop-in shadcn API
- Radix Tabs
- Motion layoutId
- Keyboard accessible
- prefers-reduced-motion
Visitors
24.8k
Signups
1,204
Conversion
4.9%
import {
AnimatedTabs,
AnimatedTabsContent,
AnimatedTabsList,
AnimatedTabsPanels,
AnimatedTabsTrigger,
} from "@/components/dusk/tabs/animated-tabs";
const stats = [
{ label: "Visitors", value: "24.8k" },
{ label: "Signups", value: "1,204" },
{ label: "Conversion", value: "4.9%" },
];
export default function AnimatedTabsDemo() {
return (
<AnimatedTabs defaultValue="overview" className="w-full max-w-md">
<AnimatedTabsList>
<AnimatedTabsTrigger value="overview">Overview</AnimatedTabsTrigger>
<AnimatedTabsTrigger value="activity">Activity</AnimatedTabsTrigger>
<AnimatedTabsTrigger value="settings">Settings</AnimatedTabsTrigger>
</AnimatedTabsList>
<AnimatedTabsPanels>
<AnimatedTabsContent value="overview" className="grid grid-cols-3 gap-2">
{stats.map((s) => (
<div key={s.label} className="rounded-xl border bg-card p-3">
<p className="text-xs text-muted-foreground">{s.label}</p>
<p className="mt-1 text-lg font-semibold tabular-nums">{s.value}</p>
</div>
))}
</AnimatedTabsContent>
<AnimatedTabsContent value="activity" className="rounded-xl border bg-card p-4">
<ul className="space-y-3 text-sm">
<li><span className="font-medium text-foreground">Mia</span> deployed <span className="font-mono text-xs">v2.4.0</span></li>
<li><span className="font-medium text-foreground">Leo</span> merged “Animated tabs”</li>
<li><span className="font-medium text-foreground">Ava</span> invited 3 teammates</li>
<li><span className="font-medium text-foreground">Kai</span> rotated the API key</li>
</ul>
</AnimatedTabsContent>
<AnimatedTabsContent value="settings" className="rounded-xl border bg-card p-4 text-sm text-muted-foreground">
Notifications are on for deploys and mentions.
</AnimatedTabsContent>
</AnimatedTabsPanels>
</AnimatedTabs>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/tabs.json1. Install the dependencies.
npm install @radix-ui/react-tabs class-variance-authority2. Copy the source into
components/ui/tabs.tsx.tabs.tsx "use client"; import * as React from "react"; import * as TabsPrimitive from "@radix-ui/react-tabs"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; /** * DuskUI Tabs — a drop-in upgrade of the shadcn/ui Tabs. * * Same parts, props and data-slot attributes as shadcn (Tabs, TabsList, * TabsTrigger, TabsContent) plus: * - `variant` on TabsList: `default` (segmented surface) or `line` (an * underline that grows in under the active trigger). * - Vertical orientation styles out of the box (`orientation="vertical"`). * - Panels fade in when they become active, and show a focus ring * when focused from the keyboard. * - Hover, active and focus-visible states with smooth color transitions. * - Under `prefers-reduced-motion` panels appear instantly. * CSS only (tw-animate-css), powered by Radix for roving focus and aria. */ function Tabs({ className, orientation = "horizontal", ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) { return ( <TabsPrimitive.Root data-slot="tabs" orientation={orientation} className={cn("flex gap-2 data-[orientation=horizontal]:flex-col", className)} {...props} /> ); } const tabsListVariants = cva( [ "inline-flex w-fit items-center justify-center text-muted-foreground", "data-[orientation=vertical]:h-fit data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch", ], { variants: { variant: { default: "h-9 rounded-lg bg-muted p-[3px] data-[orientation=vertical]:gap-0.5", line: "h-9 gap-1 border-b border-border data-[orientation=vertical]:gap-0.5 data-[orientation=vertical]:border-b-0 data-[orientation=vertical]:border-s", }, }, defaultVariants: { variant: "default", }, } ); const tabsTriggerVariants = cva( [ "relative inline-flex flex-1 items-center justify-center gap-1.5 whitespace-nowrap rounded-md border border-transparent px-2.5 py-1 text-sm font-medium text-muted-foreground outline-none select-none", "transition-[color,background-color,border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none", "hover:text-foreground data-[state=active]:text-foreground", "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50", "disabled:pointer-events-none disabled:opacity-50", "data-[orientation=vertical]:w-full data-[orientation=vertical]:flex-none data-[orientation=vertical]:justify-start", "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", ], { variants: { variant: { default: [ "h-[calc(100%-1px)] data-[orientation=vertical]:h-8", "data-[state=active]:border-white/10 data-[state=active]:bg-background", "data-[state=active]:shadow-sm", ], line: [ "h-full rounded-b-none data-[orientation=vertical]:h-8 data-[orientation=vertical]:rounded-s-none data-[orientation=vertical]:rounded-e-md", // The underline: grows from the center on the active trigger. "after:pointer-events-none after:absolute after:inset-x-1.5 after:-bottom-px after:h-0.5 after:rounded-full after:bg-primary", "after:scale-x-0 after:transition-[scale] after:duration-200 after:ease-out data-[state=active]:after:scale-x-100", "data-[orientation=vertical]:after:inset-x-auto data-[orientation=vertical]:after:inset-y-1.5 data-[orientation=vertical]:after:-start-px data-[orientation=vertical]:after:bottom-auto data-[orientation=vertical]:after:h-auto data-[orientation=vertical]:after:w-0.5", "data-[orientation=vertical]:after:scale-x-100 data-[orientation=vertical]:after:scale-y-0 data-[orientation=vertical]:data-[state=active]:after:scale-y-100", "motion-reduce:after:transition-none", ], }, }, defaultVariants: { variant: "default", }, } ); type TabsVariant = NonNullable<VariantProps<typeof tabsListVariants>["variant"]>; const TabsVariantContext = React.createContext<TabsVariant>("default"); /** The row (or column) of triggers. `variant="line"` swaps the segmented surface for an underline. */ function TabsList({ className, variant, ...props }: React.ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants>) { const resolved = variant ?? "default"; return ( <TabsVariantContext.Provider value={resolved}> <TabsPrimitive.List data-slot="tabs-list" data-variant={resolved} className={cn(tabsListVariants({ variant: resolved }), className)} {...props} /> </TabsVariantContext.Provider> ); } /** A button that activates its panel. Arrow keys move between triggers. */ function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) { const variant = React.useContext(TabsVariantContext); return ( <TabsPrimitive.Trigger data-slot="tabs-trigger" className={cn(tabsTriggerVariants({ variant }), className)} {...props} /> ); } /** The panel shown when its `value` is active. */ function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) { return ( <TabsPrimitive.Content data-slot="tabs-content" className={cn( "flex-1 rounded-md outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50", "data-[state=active]:animate-in data-[state=active]:fade-in-0 data-[state=active]:duration-200 data-[state=active]:ease-out", "motion-reduce:data-[state=active]:animate-none", className )} {...props} /> ); } export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants, tabsTriggerVariants };
Replaces components/ui/tabs.tsx with the same parts and data-slot attributes, so existing tabs keep working. The base Tabs animates with CSS only (tw-animate-css).
Usage
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
export function SettingsTabs() {
return (
<Tabs defaultValue="account">
<TabsList>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="password">Password</TabsTrigger>
</TabsList>
<TabsContent value="account">Edit your profile.</TabsContent>
<TabsContent value="password">Change your password.</TabsContent>
</Tabs>
)
}Examples
Default
A segmented trigger row with a raised active tab. Panels fade and rise in, and show a focus ring when reached with Tab.
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
export default function TabsBasicDemo() {
return (
<Tabs defaultValue="account" className="w-full max-w-sm">
<TabsList>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="password">Password</TabsTrigger>
</TabsList>
<TabsContent value="account" className="grid gap-3 rounded-xl border bg-card p-4">
<label className="grid gap-1.5 text-sm font-medium">
Name
<Input defaultValue="Ada Lovelace" />
</label>
<Button size="sm" className="justify-self-end">Save</Button>
</TabsContent>
<TabsContent value="password" className="grid gap-3 rounded-xl border bg-card p-4">
<label className="grid gap-1.5 text-sm font-medium">
New password
<Input type="password" autoComplete="new-password" />
</label>
<Button size="sm" className="justify-self-end">Update password</Button>
</TabsContent>
</Tabs>
);
}Line variant
variant="line" on TabsList swaps the surface for an underline that grows from the center of the active trigger. Icons size themselves.
import { Code2, Eye, MessageSquare } from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
export default function TabsLineDemo() {
return (
<Tabs defaultValue="preview" className="w-full max-w-md">
<TabsList variant="line">
<TabsTrigger value="preview">
<Eye /> Preview
</TabsTrigger>
<TabsTrigger value="code">
<Code2 /> Code
</TabsTrigger>
<TabsTrigger value="comments">
<MessageSquare /> Comments
</TabsTrigger>
</TabsList>
<TabsContent value="preview" className="pt-2 text-sm text-muted-foreground">
The rendered component, live.
</TabsContent>
<TabsContent value="code" className="pt-2 text-sm text-muted-foreground">
Copy-paste source with syntax highlighting.
</TabsContent>
<TabsContent value="comments" className="pt-2 text-sm text-muted-foreground">
3 comments from your team.
</TabsContent>
</Tabs>
);
}Vertical
Set orientation="vertical" on Tabs for settings-style navigation. Up and Down arrows move between triggers; with the line variant the indicator becomes a side bar.
General
Workspace name, URL and default language.
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
const sections = [
{ value: "general", label: "General", body: "Workspace name, URL and default language." },
{ value: "members", label: "Members", body: "Invite people and manage their roles." },
{ value: "billing", label: "Billing", body: "Plan, invoices and payment method." },
];
export default function TabsVerticalDemo() {
return (
<Tabs defaultValue="general" orientation="vertical" className="w-full max-w-md gap-6">
<TabsList variant="line" className="w-36">
{sections.map((s) => (
<TabsTrigger key={s.value} value={s.value}>
{s.label}
</TabsTrigger>
))}
</TabsList>
{sections.map((s) => (
<TabsContent key={s.value} value={s.value} className="p-1">
<h3 className="font-medium">{s.label}</h3>
<p className="mt-1 text-sm text-muted-foreground">{s.body}</p>
</TabsContent>
))}
</Tabs>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Animated Tabs
The active indicator (a pill or an underline) glides between triggers via a shared Motion layoutId, and panels slide in slightly from the direction you're travelling while the old panel leaves the other way. AnimatedTabsPanels springs to the new panel's height so nothing below jumps. Same composition as shadcn Tabs.
Visitors
24.8k
Signups
1,204
Conversion
4.9%
import {
AnimatedTabs,
AnimatedTabsContent,
AnimatedTabsList,
AnimatedTabsPanels,
AnimatedTabsTrigger,
} from "@/components/dusk/tabs/animated-tabs";
const stats = [
{ label: "Visitors", value: "24.8k" },
{ label: "Signups", value: "1,204" },
{ label: "Conversion", value: "4.9%" },
];
export default function AnimatedTabsDemo() {
return (
<AnimatedTabs defaultValue="overview" className="w-full max-w-md">
<AnimatedTabsList>
<AnimatedTabsTrigger value="overview">Overview</AnimatedTabsTrigger>
<AnimatedTabsTrigger value="activity">Activity</AnimatedTabsTrigger>
<AnimatedTabsTrigger value="settings">Settings</AnimatedTabsTrigger>
</AnimatedTabsList>
<AnimatedTabsPanels>
<AnimatedTabsContent value="overview" className="grid grid-cols-3 gap-2">
{stats.map((s) => (
<div key={s.label} className="rounded-xl border bg-card p-3">
<p className="text-xs text-muted-foreground">{s.label}</p>
<p className="mt-1 text-lg font-semibold tabular-nums">{s.value}</p>
</div>
))}
</AnimatedTabsContent>
<AnimatedTabsContent value="activity" className="rounded-xl border bg-card p-4">
<ul className="space-y-3 text-sm">
<li><span className="font-medium text-foreground">Mia</span> deployed <span className="font-mono text-xs">v2.4.0</span></li>
<li><span className="font-medium text-foreground">Leo</span> merged “Animated tabs”</li>
<li><span className="font-medium text-foreground">Ava</span> invited 3 teammates</li>
<li><span className="font-medium text-foreground">Kai</span> rotated the API key</li>
</ul>
</AnimatedTabsContent>
<AnimatedTabsContent value="settings" className="rounded-xl border bg-card p-4 text-sm text-muted-foreground">
Notifications are on for deploys and mentions.
</AnimatedTabsContent>
</AnimatedTabsPanels>
</AnimatedTabs>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-tabs.json1. Install the dependencies.
npm install motion @radix-ui/react-tabs2. Copy the source into
components/dusk/tabs/animated-tabs.tsx.animated-tabs.tsx "use client"; import * as React from "react"; import * as TabsPrimitive from "@radix-ui/react-tabs"; import { AnimatePresence, LayoutGroup, motion, useReducedMotion, type Transition, type Variants, } from "motion/react"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { cn } from "@/lib/utils"; type Indicator = "pill" | "underline"; type AnimatedTabsContextValue = { value: string; /** -1 when moving to a trigger on the left, 1 to the right, 0 initially. */ direction: number; indicator: Indicator; }; const AnimatedTabsContext = React.createContext<AnimatedTabsContextValue | null>(null); function useAnimatedTabs() { const context = React.useContext(AnimatedTabsContext); if (!context) throw new Error("AnimatedTabs parts must be used inside <AnimatedTabs>."); return context; } const indicatorSpring: Transition = { type: "spring", bounce: 0.1, duration: 0.3 }; const panelSpring: Transition = { type: "spring", bounce: 0, duration: 0.3 }; export interface AnimatedTabsProps extends Omit<React.ComponentProps<typeof Tabs>, "value" | "defaultValue" | "onValueChange"> { value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Shape of the active indicator that glides between triggers. */ indicator?: Indicator; } /** * Tabs with an indicator (pill or underline) that glides between triggers * and panels that slide in from the direction you're travelling. The panel * area springs to the new height, so content below never jumps. * * Compose it like shadcn Tabs: AnimatedTabs › AnimatedTabsList › * AnimatedTabsTrigger, then AnimatedTabsPanels › AnimatedTabsContent. * Built on the DuskUI Tabs (Radix), so arrow keys, Home/End and aria work as usual. */ export function AnimatedTabs({ value: valueProp, defaultValue = "", onValueChange, indicator = "pill", children, ...props }: AnimatedTabsProps) { const layoutId = React.useId(); const rootRef = React.useRef<HTMLDivElement>(null); const [uncontrolled, setUncontrolled] = React.useState(defaultValue); const [direction, setDirection] = React.useState(0); const value = valueProp ?? uncontrolled; const handleValueChange = (next: string) => { // Direction comes from the triggers' DOM order, so any markup works. const root = rootRef.current; const order = Array.from(root?.querySelectorAll<HTMLElement>("[data-animated-tab]") ?? []) .filter((el) => el.closest('[data-slot="tabs"]') === root) .map((el) => el.dataset.animatedTab); setDirection(Math.sign(order.indexOf(next) - order.indexOf(value))); if (valueProp === undefined) setUncontrolled(next); onValueChange?.(next); }; return ( <AnimatedTabsContext.Provider value={{ value, direction, indicator }}> <LayoutGroup id={layoutId}> <Tabs ref={rootRef} value={value} onValueChange={handleValueChange} {...props}> {children} </Tabs> </LayoutGroup> </AnimatedTabsContext.Provider> ); } /** The trigger row. Inherits the indicator style from AnimatedTabs. */ export function AnimatedTabsList({ className, ...props }: React.ComponentProps<typeof TabsList>) { const { indicator } = useAnimatedTabs(); return ( <TabsList variant={indicator === "underline" ? "line" : "default"} className={cn(indicator === "pill" && "h-10 bg-muted/70 p-1", className)} {...props} /> ); } /** A trigger. The indicator is rendered inside the active one and glides via a shared layoutId. */ export function AnimatedTabsTrigger({ value, className, children, ...props }: React.ComponentProps<typeof TabsTrigger>) { const { value: active, indicator } = useAnimatedTabs(); const isActive = active === value; return ( <TabsTrigger value={value} data-animated-tab={value} className={cn( // Replace the base active surface / underline with the moving indicator. "isolate data-[state=active]:border-transparent data-[state=active]:bg-transparent data-[state=active]:shadow-none after:hidden", "px-3 data-[state=active]:text-foreground", className )} {...props} > {isActive && ( <motion.span layoutId="animated-tabs-indicator" aria-hidden transition={indicatorSpring} className={cn( "pointer-events-none absolute -z-10", indicator === "pill" ? "inset-0 rounded-md border border-white/10 bg-background shadow-sm" : "inset-x-1.5 -bottom-px h-0.5 rounded-full bg-primary" )} /> )} {children} </TabsTrigger> ); } /** * Wraps the panels. Stacks them in one grid cell so the outgoing and incoming * panels can cross, and springs its height to the active panel. */ export function AnimatedTabsPanels({ className, children, ...props }: React.ComponentProps<"div">) { const reduceMotion = useReducedMotion(); const innerRef = React.useRef<HTMLDivElement>(null); const [height, setHeight] = React.useState<number | "auto">("auto"); React.useLayoutEffect(() => { const el = innerRef.current; if (!el) return; const observer = new ResizeObserver(([entry]) => setHeight(entry.borderBoxSize?.[0]?.blockSize ?? el.offsetHeight) ); observer.observe(el); return () => observer.disconnect(); }, []); return ( <motion.div data-slot="animated-tabs-panels" initial={false} animate={{ height }} transition={reduceMotion ? { duration: 0 } : panelSpring} className={cn("relative", className)} {...(props as React.ComponentProps<typeof motion.div>)} > <div ref={innerRef} className="grid *:col-start-1 *:row-start-1"> {children} </div> </motion.div> ); } /** A panel. Slides in slightly from the side of travel; the old panel leaves the other way. */ export function AnimatedTabsContent({ value, className, children, ...props }: Omit<React.ComponentProps<typeof TabsPrimitive.Content>, "forceMount" | "asChild">) { const { value: active, direction } = useAnimatedTabs(); const reduceMotion = useReducedMotion(); const offset = reduceMotion ? 0 : 8; const variants: Variants = { enter: (dir: number) => ({ opacity: 0, x: dir * offset }), center: { opacity: 1, x: 0 }, exit: (dir: number) => ({ opacity: 0, x: dir * -offset }), }; return ( <AnimatePresence initial={false} custom={direction}> {active === value && ( <TabsPrimitive.Content key={value} value={value} forceMount asChild {...props}> <motion.div data-slot="tabs-content" custom={direction} variants={variants} initial="enter" animate="center" exit="exit" transition={panelSpring} className={cn( "rounded-md outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50", // The outgoing panel stays visible for a moment; keep it from catching clicks. "data-[state=inactive]:pointer-events-none", className )} > {children} </motion.div> </TabsPrimitive.Content> )} </AnimatePresence> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| indicator | "pill" | "underline" | "pill" | Shape of the gliding indicator (on AnimatedTabs). |
| value / onValueChange | string / (value: string) => void | — | Controlled active tab (on AnimatedTabs). |
| defaultValue | string | — | Uncontrolled initial tab. |
| orientation / dir / activationMode | Radix Tabs props | — | Forwarded to the Radix root. |
| AnimatedTabsList / AnimatedTabsTrigger | TabsList / TabsTrigger props | — | The trigger row and its buttons. |
| AnimatedTabsPanels | div props | — | Wrap the panels: stacks them for crossfades and animates height. |
| AnimatedTabsContent | Radix TabsContent props | — | A panel. Put it directly inside AnimatedTabsPanels. |
Animated Tabs — underline
The same block with indicator="underline": a thin primary line slides under the active trigger. Panels of different heights resize smoothly.
$24
For teams shipping every day. Unlimited projects and preview deployments.
import {
AnimatedTabs,
AnimatedTabsContent,
AnimatedTabsList,
AnimatedTabsPanels,
AnimatedTabsTrigger,
} from "@/components/dusk/tabs/animated-tabs";
const plans = [
{ value: "starter", label: "Starter", price: "$0", body: "For side projects and prototypes." },
{ value: "pro", label: "Pro", price: "$24", body: "For teams shipping every day. Unlimited projects and preview deployments." },
{ value: "enterprise", label: "Enterprise", price: "Custom", body: "SSO, audit logs and a dedicated support engineer." },
];
export default function AnimatedTabsUnderlineDemo() {
return (
<AnimatedTabs defaultValue="pro" indicator="underline" className="w-full max-w-md">
<AnimatedTabsList>
{plans.map((p) => (
<AnimatedTabsTrigger key={p.value} value={p.value}>
{p.label}
</AnimatedTabsTrigger>
))}
</AnimatedTabsList>
<AnimatedTabsPanels>
{plans.map((p) => (
<AnimatedTabsContent key={p.value} value={p.value} className="py-3">
<p className="text-3xl font-semibold tracking-tight">{p.price}</p>
<p className="mt-1 text-sm text-muted-foreground">{p.body}</p>
</AnimatedTabsContent>
))}
</AnimatedTabsPanels>
</AnimatedTabs>
);
}$ npx shadcn@latest add https://duskui.com/r/animated-tabs.json1. Install the dependencies.
npm install motion @radix-ui/react-tabs2. Copy the source into
components/dusk/tabs/animated-tabs.tsx.animated-tabs.tsx "use client"; import * as React from "react"; import * as TabsPrimitive from "@radix-ui/react-tabs"; import { AnimatePresence, LayoutGroup, motion, useReducedMotion, type Transition, type Variants, } from "motion/react"; import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { cn } from "@/lib/utils"; type Indicator = "pill" | "underline"; type AnimatedTabsContextValue = { value: string; /** -1 when moving to a trigger on the left, 1 to the right, 0 initially. */ direction: number; indicator: Indicator; }; const AnimatedTabsContext = React.createContext<AnimatedTabsContextValue | null>(null); function useAnimatedTabs() { const context = React.useContext(AnimatedTabsContext); if (!context) throw new Error("AnimatedTabs parts must be used inside <AnimatedTabs>."); return context; } const indicatorSpring: Transition = { type: "spring", bounce: 0.1, duration: 0.3 }; const panelSpring: Transition = { type: "spring", bounce: 0, duration: 0.3 }; export interface AnimatedTabsProps extends Omit<React.ComponentProps<typeof Tabs>, "value" | "defaultValue" | "onValueChange"> { value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Shape of the active indicator that glides between triggers. */ indicator?: Indicator; } /** * Tabs with an indicator (pill or underline) that glides between triggers * and panels that slide in from the direction you're travelling. The panel * area springs to the new height, so content below never jumps. * * Compose it like shadcn Tabs: AnimatedTabs › AnimatedTabsList › * AnimatedTabsTrigger, then AnimatedTabsPanels › AnimatedTabsContent. * Built on the DuskUI Tabs (Radix), so arrow keys, Home/End and aria work as usual. */ export function AnimatedTabs({ value: valueProp, defaultValue = "", onValueChange, indicator = "pill", children, ...props }: AnimatedTabsProps) { const layoutId = React.useId(); const rootRef = React.useRef<HTMLDivElement>(null); const [uncontrolled, setUncontrolled] = React.useState(defaultValue); const [direction, setDirection] = React.useState(0); const value = valueProp ?? uncontrolled; const handleValueChange = (next: string) => { // Direction comes from the triggers' DOM order, so any markup works. const root = rootRef.current; const order = Array.from(root?.querySelectorAll<HTMLElement>("[data-animated-tab]") ?? []) .filter((el) => el.closest('[data-slot="tabs"]') === root) .map((el) => el.dataset.animatedTab); setDirection(Math.sign(order.indexOf(next) - order.indexOf(value))); if (valueProp === undefined) setUncontrolled(next); onValueChange?.(next); }; return ( <AnimatedTabsContext.Provider value={{ value, direction, indicator }}> <LayoutGroup id={layoutId}> <Tabs ref={rootRef} value={value} onValueChange={handleValueChange} {...props}> {children} </Tabs> </LayoutGroup> </AnimatedTabsContext.Provider> ); } /** The trigger row. Inherits the indicator style from AnimatedTabs. */ export function AnimatedTabsList({ className, ...props }: React.ComponentProps<typeof TabsList>) { const { indicator } = useAnimatedTabs(); return ( <TabsList variant={indicator === "underline" ? "line" : "default"} className={cn(indicator === "pill" && "h-10 bg-muted/70 p-1", className)} {...props} /> ); } /** A trigger. The indicator is rendered inside the active one and glides via a shared layoutId. */ export function AnimatedTabsTrigger({ value, className, children, ...props }: React.ComponentProps<typeof TabsTrigger>) { const { value: active, indicator } = useAnimatedTabs(); const isActive = active === value; return ( <TabsTrigger value={value} data-animated-tab={value} className={cn( // Replace the base active surface / underline with the moving indicator. "isolate data-[state=active]:border-transparent data-[state=active]:bg-transparent data-[state=active]:shadow-none after:hidden", "px-3 data-[state=active]:text-foreground", className )} {...props} > {isActive && ( <motion.span layoutId="animated-tabs-indicator" aria-hidden transition={indicatorSpring} className={cn( "pointer-events-none absolute -z-10", indicator === "pill" ? "inset-0 rounded-md border border-white/10 bg-background shadow-sm" : "inset-x-1.5 -bottom-px h-0.5 rounded-full bg-primary" )} /> )} {children} </TabsTrigger> ); } /** * Wraps the panels. Stacks them in one grid cell so the outgoing and incoming * panels can cross, and springs its height to the active panel. */ export function AnimatedTabsPanels({ className, children, ...props }: React.ComponentProps<"div">) { const reduceMotion = useReducedMotion(); const innerRef = React.useRef<HTMLDivElement>(null); const [height, setHeight] = React.useState<number | "auto">("auto"); React.useLayoutEffect(() => { const el = innerRef.current; if (!el) return; const observer = new ResizeObserver(([entry]) => setHeight(entry.borderBoxSize?.[0]?.blockSize ?? el.offsetHeight) ); observer.observe(el); return () => observer.disconnect(); }, []); return ( <motion.div data-slot="animated-tabs-panels" initial={false} animate={{ height }} transition={reduceMotion ? { duration: 0 } : panelSpring} className={cn("relative", className)} {...(props as React.ComponentProps<typeof motion.div>)} > <div ref={innerRef} className="grid *:col-start-1 *:row-start-1"> {children} </div> </motion.div> ); } /** A panel. Slides in slightly from the side of travel; the old panel leaves the other way. */ export function AnimatedTabsContent({ value, className, children, ...props }: Omit<React.ComponentProps<typeof TabsPrimitive.Content>, "forceMount" | "asChild">) { const { value: active, direction } = useAnimatedTabs(); const reduceMotion = useReducedMotion(); const offset = reduceMotion ? 0 : 8; const variants: Variants = { enter: (dir: number) => ({ opacity: 0, x: dir * offset }), center: { opacity: 1, x: 0 }, exit: (dir: number) => ({ opacity: 0, x: dir * -offset }), }; return ( <AnimatePresence initial={false} custom={direction}> {active === value && ( <TabsPrimitive.Content key={value} value={value} forceMount asChild {...props}> <motion.div data-slot="tabs-content" custom={direction} variants={variants} initial="enter" animate="center" exit="exit" transition={panelSpring} className={cn( "rounded-md outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50", // The outgoing panel stays visible for a moment; keep it from catching clicks. "data-[state=inactive]:pointer-events-none", className )} > {children} </motion.div> </TabsPrimitive.Content> )} </AnimatePresence> ); }
Segmented Control
An iOS-style picker for a single value — view mode, billing period, units. A raised thumb springs between options. It is a native radio group, so arrow keys work, the value submits with forms via name, and screen readers announce it as radio buttons. Use Animated Tabs when each option shows its own panel.
View: grid
"use client";
import * as React from "react";
import { LayoutGrid, List, Rows3 } from "lucide-react";
import { SegmentedControl } from "@/components/dusk/tabs/segmented-control";
export default function SegmentedControlDemo() {
const [view, setView] = React.useState("grid");
return (
<div className="grid justify-items-center gap-6">
<SegmentedControl
aria-label="View"
value={view}
onValueChange={setView}
options={[
{ value: "grid", label: "Grid", icon: <LayoutGrid /> },
{ value: "list", label: "List", icon: <List /> },
{ value: "rows", label: "Compact", icon: <Rows3 /> },
]}
/>
<SegmentedControl
aria-label="Billing period"
size="sm"
defaultValue="yearly"
name="billing"
options={[
{ value: "monthly", label: "Monthly" },
{ value: "yearly", label: "Yearly · save 20%" },
]}
/>
<p className="text-xs text-muted-foreground" aria-live="polite">
View: <span className="text-foreground">{view}</span>
</p>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/segmented-control.json1. Install the dependencies.
npm install motion2. Copy the source into
components/dusk/tabs/segmented-control.tsx.segmented-control.tsx "use client"; import * as React from "react"; import { LayoutGroup, motion, type Transition } from "motion/react"; import { cn } from "@/lib/utils"; export interface SegmentedControlOption { value: string; label: React.ReactNode; /** Optional leading icon element, e.g. `<List />`. */ icon?: React.ReactNode; disabled?: boolean; } export interface SegmentedControlProps extends Omit<React.ComponentProps<"div">, "onChange" | "defaultValue" | "dir"> { options: SegmentedControlOption[]; value?: string; defaultValue?: string; onValueChange?: (value: string) => void; /** Form field name. The selected value is submitted with the form. */ name?: string; size?: "sm" | "default" | "lg"; disabled?: boolean; /** Stretch to the container's width with equal segments. */ fullWidth?: boolean; } const thumbSpring: Transition = { type: "spring", bounce: 0.1, duration: 0.3 }; const sizes = { sm: "h-7 px-2.5 text-xs gap-1 [&_svg:not([class*='size-'])]:size-3.5", default: "h-8 px-3 text-sm gap-1.5 [&_svg:not([class*='size-'])]:size-4", lg: "h-10 px-4 text-sm gap-2 [&_svg:not([class*='size-'])]:size-4", } as const; /** * An iOS-style segmented control: a raised thumb springs between options. * It is a real radio group (native `<input type="radio">`), so arrow keys, * form submission and screen readers work without extra code. Use it to pick * a value (view mode, billing period, units); use Animated Tabs to switch panels. */ export function SegmentedControl({ options, value: valueProp, defaultValue, onValueChange, name, size = "default", disabled = false, fullWidth = false, className, ...props }: SegmentedControlProps) { const id = React.useId(); const [uncontrolled, setUncontrolled] = React.useState(defaultValue ?? options[0]?.value ?? ""); const value = valueProp ?? uncontrolled; const select = (next: string) => { if (valueProp === undefined) setUncontrolled(next); onValueChange?.(next); }; return ( <LayoutGroup id={id}> <div role="radiogroup" aria-disabled={disabled || undefined} data-slot="segmented-control" className={cn( "relative isolate inline-flex w-fit items-center rounded-lg bg-muted p-1", fullWidth && "flex w-full", disabled && "opacity-50", className )} {...props} > {options.map((option) => { const checked = option.value === value; const isDisabled = disabled || option.disabled; return ( <label key={option.value} data-state={checked ? "checked" : "unchecked"} className={cn( "relative inline-flex cursor-pointer items-center justify-center whitespace-nowrap rounded-md font-medium text-muted-foreground select-none", "transition-[color,box-shadow] duration-200 ease-out motion-reduce:transition-none", "hover:text-foreground data-[state=checked]:text-foreground", "has-focus-visible:ring-[3px] has-focus-visible:ring-ring/50", "has-disabled:cursor-not-allowed has-disabled:opacity-50 has-disabled:hover:text-muted-foreground", "[&_svg]:pointer-events-none [&_svg]:shrink-0", sizes[size], fullWidth && "flex-1" )} > <input type="radio" name={name ?? id} value={option.value} checked={checked} disabled={isDisabled} onChange={() => select(option.value)} className="sr-only" /> {checked && ( <motion.span layoutId="segmented-thumb" aria-hidden transition={thumbSpring} className="pointer-events-none absolute inset-0 -z-10 rounded-md border border-white/10 bg-background shadow-sm" /> )} {option.icon} <span>{option.label}</span> </label> ); })} </div> </LayoutGroup> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| options | { value, label, icon?, disabled? }[] | — | The segments. `icon` is an element, e.g. <List />. |
| value / onValueChange | string / (value: string) => void | — | Controlled selection. |
| defaultValue | string | first option | Uncontrolled initial selection. |
| name | string | — | Form field name; the selected value is submitted. |
| size | "sm" | "default" | "lg" | "default" | Height and text size. |
| fullWidth | boolean | false | Stretch to the container with equal segments. |
| disabled | boolean | false | Disable every option. |
| aria-label | string | — | Names the radio group. Required unless labelled elsewhere. |
API Reference
Same parts as shadcn/ui: Tabs, TabsList, TabsTrigger and TabsContent, each forwarding its Radix Tabs props. The additions are below.
| Prop | Type | Default | Description |
|---|---|---|---|
| variant | "default" | "line" | "default" | On TabsList: segmented surface or underline. |
| orientation | "horizontal" | "vertical" | "horizontal" | On Tabs: lays out the list beside the panels and switches arrow keys to Up / Down. |
| value / onValueChange | string / (value: string) => void | — | Controlled active tab (on Tabs). |
| activationMode | "automatic" | "manual" | "automatic" | Activate on focus, or only on Enter / Space. |
| tabsListVariants / tabsTriggerVariants | cva | — | Exported class builders for custom triggers. |
Accessibility
- Built on Radix Tabs: triggers are a tablist with roving focus (arrow keys, Home, End) and panels are linked with aria-controls / aria-labelledby.
- Panels are focusable and show a focus-visible ring, so keyboard users can Tab from the trigger into the content.
- The gliding indicators are decorative, aria-hidden and pointer-events-none; the active state is conveyed by aria-selected.
- Segmented Control uses native radio inputs inside a radiogroup — label it with aria-label or aria-labelledby.
- Under prefers-reduced-motion panels only fade, the indicator jumps instead of gliding and the height change is instant.