Skip to content

Expandable Tabs

Icon tabs expand into labeled pills; content morphs height.

Installation

CLI

npx shadcn@latest add https://hantui-theta.vercel.app/r/expandable-tabs.json

Manual

  1. Install the dependencies

    npm install clsx motion tailwind-merge
  2. Add the shared helpers

    Components use cn() from lib/utils.ts and the motion tokens below. See Installation if you have not set them up yet.

    lib/motion.ts
    import type { Transition, Variants } from "motion/react";
    
    /** Durations in seconds. */
    export const duration = {
      instant: 0.1,
      quick: 0.18,
      base: 0.28,
      slow: 0.45,
    } as const;
    
    /** Cubic-bezier curves. */
    export const ease = {
      /** Entering, UI response. */
      out: [0.22, 1, 0.36, 1],
      /** Moving on screen. */
      inOut: [0.65, 0, 0.35, 1],
      /** Sheets and the mobile menu. */
      drawer: [0.32, 0.72, 0, 1],
    } as const;
    
    /** Everyday UI: presses, icon swaps, popovers and modals. Exits run at `exitFactor` of the enter. */
    export const ui = {
      press: { scale: 0.96, duration: 0.12 },
      icon: { type: "spring", duration: 0.3, bounce: 0 },
      popover: { duration: 0.18, ease: ease.out },
      modal: { duration: 0.24, ease: ease.out },
      exitFactor: 0.6,
    } as const;
    
    /** Once-per-visit motion on the landing page: hero letters, the reel and the afterimage. */
    export const kinetic = {
      heroLetter: { duration: 0.6, ease: ease.out },
      /** Delay per letter, eased so the wave slows toward the end. */
      heroStep: 0.035,
      reelSwap: { type: "spring", duration: 0.5, bounce: 0.1 },
      /** Two afterimages: lag in seconds and opacity of each. */
      ghost: { lag: [0.04, 0.09], opacity: [0.14, 0.06] },
    } as const;
    
    /** Spring presets. */
    export const spring = {
      snappy: { type: "spring", stiffness: 500, damping: 30 },
      smooth: { type: "spring", stiffness: 260, damping: 26 },
      bouncy: { type: "spring", stiffness: 300, damping: 15 },
    } as const satisfies Record<string, Transition>;
    
    /** Stagger between siblings, in seconds (0.03–0.06). */
    export const stagger = {
      tight: 0.03,
      base: 0.045,
      loose: 0.06,
    } as const;
    
    /** Blur + fade + y-offset. Falls back to a plain fade under reduced motion. */
    export function enterVariants(reduceMotion?: boolean | null, y = 8): Variants {
      if (reduceMotion) {
        return {
          hidden: { opacity: 0 },
          visible: { opacity: 1, transition: { duration: duration.base } },
          exit: { opacity: 0, transition: { duration: duration.quick } },
        };
      }
      return {
        hidden: { opacity: 0, y, filter: "blur(4px)" },
        visible: {
          opacity: 1,
          y: 0,
          filter: "blur(0px)",
          transition: { duration: duration.base, ease: ease.out },
        },
        exit: {
          opacity: 0,
          y: -y / 2,
          filter: "blur(4px)",
          transition: { duration: duration.quick, ease: ease.out },
        },
      };
    }
    
    /** Scale 0.96 → 1 for popovers, menus and dialogs. */
    export function overlayVariants(reduceMotion?: boolean | null): Variants {
      if (reduceMotion) {
        return {
          hidden: { opacity: 0 },
          visible: { opacity: 1, transition: { duration: duration.quick } },
          exit: { opacity: 0, transition: { duration: duration.instant } },
        };
      }
      return {
        hidden: { opacity: 0, scale: 0.96, filter: "blur(2px)" },
        visible: {
          opacity: 1,
          scale: 1,
          filter: "blur(0px)",
          transition: { duration: duration.quick, ease: ease.out },
        },
        exit: {
          opacity: 0,
          scale: 0.96,
          filter: "blur(2px)",
          transition: { duration: duration.instant + 0.02, ease: ease.out },
        },
      };
    }
    
    /** Parent variants that stagger their children in. */
    export function staggerVariants(gap: number = stagger.base, delayChildren = 0): Variants {
      return {
        hidden: {},
        visible: { transition: { staggerChildren: gap, delayChildren } },
        exit: { transition: { staggerChildren: gap / 2, staggerDirection: -1 } },
      };
    }
  3. Copy the source

    components/ui/expandable-tabs/expandable-tabs.tsx
    "use client";
    
    import { useId, useRef, useState, type ComponentProps, type KeyboardEvent, type ReactNode } from "react";
    import { AnimatePresence, LayoutGroup, motion, useReducedMotion } from "motion/react";
    import { cn } from "@/lib/utils";
    import { duration, ease } from "@/lib/motion";
    
    export interface ExpandableTabItem {
      /** Unique value for the tab. */
      value: string;
      /** Label shown while active; always used as the accessible name. */
      label: string;
      /** Icon shown at all times. */
      icon: ReactNode;
      /** Panel shown while the tab is active. Omit it to render only the bar. */
      content?: ReactNode;
    }
    
    export interface ExpandableTabsProps
      extends Omit<ComponentProps<"div">, "defaultValue" | "onChange" | "onAnimationStart" | "onDrag" | "onDragStart" | "onDragEnd"> {
      /** The tabs, in order. */
      items: ExpandableTabItem[];
      /** Controlled active tab. */
      value?: string;
      /** Initially active tab when uncontrolled. @default the first tab */
      defaultValue?: string;
      /** Called with the newly active tab. */
      onValueChange?: (value: string) => void;
      /** Color of the bar. @default "light" */
      tone?: "light" | "dark";
    }
    
    const tones = {
      light: {
        bar: "border border-border bg-background shadow-sm",
        active: "bg-foreground",
        activeText: "text-background",
        idleText: "text-muted-foreground hover:text-foreground hover:bg-accent",
      },
      dark: {
        bar: "bg-foreground shadow-lg",
        active: "bg-background/15",
        activeText: "text-background",
        idleText: "text-background/60 hover:text-background",
      },
    } as const;
    
    // One spring for every layout change, so the tab, its label and the panel move together.
    const LAYOUT = { type: "spring", stiffness: 420, damping: 36 } as const;
    
    export function ExpandableTabs({
      items,
      value,
      defaultValue,
      onValueChange,
      tone = "light",
      className,
      "aria-label": ariaLabel,
      ...props
    }: ExpandableTabsProps) {
      const [internal, setInternal] = useState(defaultValue ?? items[0]?.value);
      const active = value ?? internal;
      const reduceMotion = useReducedMotion();
      const id = useId();
      const tabRefs = useRef<(HTMLButtonElement | null)[]>([]);
      const t = tones[tone];
      const layout = reduceMotion ? { duration: 0 } : LAYOUT;
      const activeItem = items.find((item) => item.value === active);
      const tabId = (v: string) => `${id}-tab-${v}`;
      const panelId = (v: string) => `${id}-panel-${v}`;
    
      function select(next: string) {
        if (next === active) return;
        if (value === undefined) setInternal(next);
        onValueChange?.(next);
      }
    
      function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
        const index = items.findIndex((item) => item.value === active);
        const targets: Record<string, number> = {
          ArrowRight: (index + 1) % items.length,
          ArrowLeft: (index - 1 + items.length) % items.length,
          Home: 0,
          End: items.length - 1,
        };
        if (!(event.key in targets)) return;
        event.preventDefault();
        const next = targets[event.key];
        select(items[next].value);
        tabRefs.current[next]?.focus();
      }
    
      return (
        <div className={cn("w-full", className)} {...props}>
          <LayoutGroup id={id}>
            <div
              role="tablist"
              aria-label={ariaLabel}
              onKeyDown={onKeyDown}
              className={cn("inline-flex max-w-full items-center gap-1 rounded-full p-1", t.bar)}
            >
              {items.map((item, index) => {
                const isActive = item.value === active;
                return (
                  <motion.button
                    key={item.value}
                    ref={(node) => {
                      tabRefs.current[index] = node;
                    }}
                    layout
                    transition={layout}
                    type="button"
                    role="tab"
                    id={tabId(item.value)}
                    aria-label={item.label}
                    aria-selected={isActive}
                    aria-controls={isActive && item.content !== undefined ? panelId(item.value) : undefined}
                    tabIndex={isActive ? 0 : -1}
                    onClick={() => select(item.value)}
                    style={{ borderRadius: 999 }}
                    className={cn(
                      "relative flex h-9 shrink-0 cursor-pointer items-center gap-2 px-3 text-sm font-medium whitespace-nowrap outline-none",
                      "transition-colors duration-150 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
                      isActive ? t.activeText : t.idleText,
                    )}
                  >
                    {isActive ? (
                      <motion.span
                        layoutId="active-pill"
                        aria-hidden="true"
                        transition={layout}
                        style={{ borderRadius: 999 }}
                        className={cn("absolute inset-0", t.active)}
                      />
                    ) : null}
                    <motion.span layout="position" transition={layout} className="relative flex [&_svg]:size-[18px]" aria-hidden="true">
                      {item.icon}
                    </motion.span>
                    <AnimatePresence mode="popLayout" initial={false}>
                      {isActive ? (
                        <motion.span
                          key="label"
                          layout="position"
                          aria-hidden="true"
                          initial={reduceMotion ? { opacity: 0 } : { opacity: 0, x: -6, filter: "blur(4px)" }}
                          animate={{ opacity: 1, x: 0, filter: "blur(0px)" }}
                          exit={{ opacity: 0, filter: reduceMotion ? "blur(0px)" : "blur(4px)", transition: { duration: duration.instant } }}
                          transition={{ duration: duration.base, ease: ease.out, layout }}
                          className="relative"
                        >
                          {item.label}
                        </motion.span>
                      ) : null}
                    </AnimatePresence>
                  </motion.button>
                );
              })}
            </div>
    
            {activeItem?.content !== undefined ? (
              // The panel is a layout box: its height morphs (as a transform) while the content swaps inside it.
              <motion.div
                layout
                transition={layout}
                style={{ borderRadius: 16 }}
                className="relative mt-3 overflow-hidden border border-border bg-background shadow-sm"
              >
                <AnimatePresence mode="popLayout" initial={false}>
                  <motion.div
                    key={activeItem.value}
                    layout="position"
                    role="tabpanel"
                    id={panelId(activeItem.value)}
                    aria-labelledby={tabId(activeItem.value)}
                    tabIndex={0}
                    initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 8, filter: "blur(4px)" }}
                    animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
                    exit={{ opacity: 0, filter: reduceMotion ? "blur(0px)" : "blur(4px)", transition: { duration: duration.quick } }}
                    transition={{ duration: duration.base, ease: ease.out, layout }}
                    className="p-4 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
                  >
                    {activeItem.content}
                  </motion.div>
                </AnimatePresence>
              </motion.div>
            ) : null}
          </LayoutGroup>
        </div>
      );
    }

Usage

import { Home, Search } from "lucide-react";
import { ExpandableTabs } from "@/components/ui/expandable-tabs/expandable-tabs";

export function AppTabs() {
  return (
    <ExpandableTabs
      aria-label="Sections"
      items={[
        { value: "home", label: "Home", icon: <Home />, content: <HomePanel /> },
        { value: "search", label: "Search", icon: <Search />, content: <SearchPanel /> },
      ]}
    />
  );
}

API reference

PropTypeDefaultDescription
items*ExpandableTabItem[]–The tabs, in order.
valuestring–Controlled active tab.
defaultValuestringthe first tabInitially active tab when uncontrolled.
onValueChange(value: string) => void–Called with the newly active tab.
tone"light" | "dark""light"Color of the bar.

Also accepts every native <div> attribute, including ref and className.

  • Width and height changes are Motion layout animations (transforms with distortion correction), never width or height.
  • Leave out content for a compact toolbar or nav bar; use onValueChange to react to the selection.

Accessibility

  • A real tablist: each tab has role="tab", aria-selected and a roving tabindex; the panel has role="tabpanel" and is labelled by its tab.
  • Arrow keys move and activate tabs, and Home and End jump to the ends.
  • Every tab keeps its label as the accessible name (aria-label), even while only its icon is visible.
  • With reduced motion enabled, tabs and the panel resize instantly and the content cross-fades.