Skip to content
Molecules

Tabs

Tabs with a stretching indicator.

Primitive

Installation

Primitive
  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/, installs radix-ui@base-ui/react and the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.

    $ pnpm dlx asta-ui@latest add tabs --radix

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/tabs.json

  2. Or install the package

    Don’t want the file? Import from asta-uiasta-ui/base and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui radix-ui @base-ui/react
    import { Tabs } from "asta-ui";
    import { Tabs } from "asta-ui/base";
  3. Or copy it by hand

    Install radix-ui@base-ui/react, then copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { Tabs as T } from "radix-ui";
    import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface Tab {
      value: string;
      label: ReactNode;
      content: ReactNode;
      count?: number;
    }
    
    export interface TabsProps {
      tabs: Tab[];
      value?: string;
      defaultValue?: string;
      onChange?: (value: string) => void;
      /** `underline` (default): a bar that stretches between tabs. `pill`: a soft slab behind the active tab. */
      variant?: "underline" | "pill";
      label?: string;
      className?: string;
    }
    
    /**
     * Tabs on Radix Tabs (roving focus, arrows, Home/End, ARIA wiring). The indicator stretches across the gap
     * before snapping to the new tab (the leading edge moves first, the trailing edge follows), and panels cross-fade.
     */
    export function Tabs({ tabs, value, defaultValue, onChange, variant = "underline", label, className }: TabsProps) {
      const [inner, setInner] = useState(defaultValue ?? tabs[0]?.value);
      const current = value ?? inner;
      const index = Math.max(0, tabs.findIndex((t) => t.value === current));
      const refs = useRef<(HTMLButtonElement | null)[]>([]);
      const list = useRef<HTMLDivElement>(null);
      const prev = useRef(index);
      const [bar, setBar] = useState<{ l: number; r: number; dir: 1 | -1 } | null>(null);
    
      useLayoutEffect(() => {
        const measure = () => {
          const el = refs.current[index];
          const box = list.current;
          if (!el || !box) return;
          const dir = index >= prev.current ? 1 : -1;
          prev.current = index;
          setBar({ l: el.offsetLeft, r: box.scrollWidth - el.offsetLeft - el.offsetWidth, dir });
        };
        // ResizeObserver reports once right after layout, so there is no layout read while the page mounts.
        const ro = new ResizeObserver(measure);
        if (list.current) ro.observe(list.current);
        return () => ro.disconnect();
      }, [index]);
    
      // The edge in the direction of travel moves fast, the other one lags: the bar stretches, then catches up.
      const fast = "cubic-bezier(.16,1,.3,1) 0.32s";
      const slow = "cubic-bezier(.16,1,.3,1) 0.62s";
      const pill = variant === "pill";
    
      return (
        <T.Root
          value={current}
          onValueChange={(v) => {
            if (value === undefined) setInner(v);
            onChange?.(v);
          }}
          className={className}
        >
          <T.List
            ref={list}
            aria-label={label}
            className={cx("relative flex overflow-x-auto [scrollbar-width:none]", pill ? "gap-1 rounded-[10px] bg-paper-2 p-1" : "gap-5 sm:gap-6")}
          >
            {!pill && <span aria-hidden className="absolute inset-x-0 bottom-0 h-px bg-[color-mix(in_srgb,var(--color-ink)_10%,transparent)]" />}
            {bar && (
              <span
                aria-hidden
                className={cx(
                  "absolute motion-reduce:!transition-none",
                  pill ? "top-1 bottom-1 rounded-[7px] bg-paper shadow-[0_1px_2px_rgb(0_0_0/0.08),inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_8%,transparent)]" : "bottom-0 h-0.5 rounded-full bg-ink",
                )}
                // perf-ok: a 2px indicator bar; left/right animate so its ends move at different speeds, once per change.
                style={{ left: bar.l, right: bar.r, transition: `left ${bar.dir === 1 ? slow : fast}, right ${bar.dir === 1 ? fast : slow}` }}
              />
            )}
            {tabs.map((t, i) => (
              <T.Trigger
                key={t.value}
                value={t.value}
                ref={(el) => {
                  refs.current[i] = el;
                }}
                className={cx(
                  "group/tab relative z-10 inline-flex shrink-0 items-center gap-2 whitespace-nowrap text-[14px] font-medium tracking-[-0.01em] text-mute outline-none transition-colors duration-300 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 data-[state=active]:text-ink",
                  pill ? "h-8 rounded-[7px] px-3.5" : "h-11 rounded-md",
                )}
              >
                {t.label}
                {t.count !== undefined && (
                  <span className="rounded-[5px] bg-[color-mix(in_srgb,var(--color-ink)_7%,transparent)] px-1.5 text-[11px] leading-[18px] tabular-nums text-mute transition-colors duration-300 group-data-[state=active]/tab:bg-brand group-data-[state=active]/tab:text-on-brand">
                    {t.count}
                  </span>
                )}
              </T.Trigger>
            ))}
          </T.List>
          <style href="asta-tabs" precedence="asta">{`@keyframes kit-tab-in { from { opacity: 0; transform: translateY(6px) } to { opacity: 1; transform: none } }`}</style>
          {tabs.map((t) => (
            <T.Content key={t.value} value={t.value} className="pt-5 outline-none animate-[kit-tab-in_.45s_cubic-bezier(.16,1,.3,1)_both] motion-reduce:!animate-none">
              {t.content}
            </T.Content>
          ))}
        </T.Root>
      );
    }
    
    export default Tabs;
    
    "use client";
    
    import { Tabs as T } from "@base-ui/react/tabs";
    import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface Tab {
      value: string;
      label: ReactNode;
      content: ReactNode;
      count?: number;
    }
    
    export interface TabsProps {
      tabs: Tab[];
      value?: string;
      defaultValue?: string;
      onChange?: (value: string) => void;
      /** `underline` (default): a bar that stretches between tabs. `pill`: a soft slab behind the active tab. */
      variant?: "underline" | "pill";
      label?: string;
      className?: string;
    }
    
    /**
     * Tabs on Base UI Tabs (roving focus, arrows, Home/End, ARIA wiring). The indicator stretches across the gap
     * before snapping to the new tab (the leading edge moves first, the trailing edge follows), and panels cross-fade.
     */
    export function Tabs({ tabs, value, defaultValue, onChange, variant = "underline", label, className }: TabsProps) {
      const [inner, setInner] = useState(defaultValue ?? tabs[0]?.value);
      const current = value ?? inner;
      const index = Math.max(0, tabs.findIndex((t) => t.value === current));
      const refs = useRef<(HTMLElement | null)[]>([]);
      const list = useRef<HTMLDivElement>(null);
      const prev = useRef(index);
      const [bar, setBar] = useState<{ l: number; r: number; dir: 1 | -1 } | null>(null);
    
      useLayoutEffect(() => {
        const measure = () => {
          const el = refs.current[index];
          const box = list.current;
          if (!el || !box) return;
          const dir = index >= prev.current ? 1 : -1;
          prev.current = index;
          setBar({ l: el.offsetLeft, r: box.scrollWidth - el.offsetLeft - el.offsetWidth, dir });
        };
        // ResizeObserver reports once right after layout, so there is no layout read while the page mounts.
        const ro = new ResizeObserver(measure);
        if (list.current) ro.observe(list.current);
        return () => ro.disconnect();
      }, [index]);
    
      // The edge in the direction of travel moves fast, the other one lags: the bar stretches, then catches up.
      const fast = "cubic-bezier(.16,1,.3,1) 0.32s";
      const slow = "cubic-bezier(.16,1,.3,1) 0.62s";
      const pill = variant === "pill";
    
      return (
        <T.Root
          value={current}
          onValueChange={(v) => {
            const next = String(v);
            if (value === undefined) setInner(next);
            onChange?.(next);
          }}
          className={className}
        >
          <T.List
            ref={list}
            aria-label={label}
            activateOnFocus
            className={cx("relative flex overflow-x-auto [scrollbar-width:none]", pill ? "gap-1 rounded-[10px] bg-paper-2 p-1" : "gap-5 sm:gap-6")}
          >
            {!pill && <span aria-hidden className="absolute inset-x-0 bottom-0 h-px bg-[color-mix(in_srgb,var(--color-ink)_10%,transparent)]" />}
            {bar && (
              <span
                aria-hidden
                className={cx(
                  "absolute motion-reduce:!transition-none",
                  pill ? "top-1 bottom-1 rounded-[7px] bg-paper shadow-[0_1px_2px_rgb(0_0_0/0.08),inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_8%,transparent)]" : "bottom-0 h-0.5 rounded-full bg-ink",
                )}
                // perf-ok: a 2px indicator bar; left/right animate so its ends move at different speeds, once per change.
                style={{ left: bar.l, right: bar.r, transition: `left ${bar.dir === 1 ? slow : fast}, right ${bar.dir === 1 ? fast : slow}` }}
              />
            )}
            {tabs.map((t, i) => (
              <T.Tab
                key={t.value}
                value={t.value}
                ref={(el) => {
                  refs.current[i] = el;
                }}
                className={cx(
                  "group/tab relative z-10 inline-flex shrink-0 items-center gap-2 whitespace-nowrap text-[14px] font-medium tracking-[-0.01em] text-mute outline-none transition-colors duration-300 hover:text-ink focus-visible:ring-2 focus-visible:ring-brand/50 data-[active]:text-ink",
                  pill ? "h-8 rounded-[7px] px-3.5" : "h-11 rounded-md",
                )}
              >
                {t.label}
                {t.count !== undefined && (
                  <span className="rounded-[5px] bg-[color-mix(in_srgb,var(--color-ink)_7%,transparent)] px-1.5 text-[11px] leading-[18px] tabular-nums text-mute transition-colors duration-300 group-data-[active]/tab:bg-brand group-data-[active]/tab:text-on-brand">
                    {t.count}
                  </span>
                )}
              </T.Tab>
            ))}
          </T.List>
          <style href="asta-base-tabs" precedence="asta">{`@keyframes kit-tab-in { from { opacity: 0; transform: translateY(6px) } to { opacity: 1; transform: none } }`}</style>
          {tabs.map((t) => (
            <T.Panel key={t.value} value={t.value} className="pt-5 outline-none animate-[kit-tab-in_.45s_cubic-bezier(.16,1,.3,1)_both] motion-reduce:!animate-none">
              {t.content}
            </T.Panel>
          ))}
        </T.Root>
      );
    }
    
    export default Tabs;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Tabs component to my project.
    
    Tabs with a stretching indicator.
    It includes: underline, pill, keys.
    
    Install it (Radix build):
    ```sh
    pnpm dlx asta-ui@latest add tabs --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/tabs.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { Tabs } from "@/components/astabyte/tabs";
    ```
    
    Usage example and props: https://ui.astabyte.com/tabs
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package).
    - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
    Add the Astabyte UI Tabs component to my project.
    
    Tabs with a stretching indicator.
    It includes: underline, pill, keys.
    
    Install it (Base UI build):
    ```sh
    pnpm dlx asta-ui@latest add tabs
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/tabs.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { Tabs } from "@/components/astabyte/tabs";
    ```
    
    Usage example and props: https://ui.astabyte.com/tabs
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package).
    - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <div class="asta-tabs" data-asta-tabs>
      <div role="tablist" aria-label="Project" class="asta-tabs-list">
        <span class="asta-tabs-line" aria-hidden="true"></span>
        <span class="asta-tabs-indicator" data-asta-tab-indicator aria-hidden="true"></span>
        <button type="button" role="tab" class="asta-tab" id="ex-tab-a" aria-controls="ex-panel-a" aria-selected="true" tabindex="0">Overview</button>
        <button type="button" role="tab" class="asta-tab" id="ex-tab-b" aria-controls="ex-panel-b" aria-selected="false" tabindex="-1">Activity <span class="asta-tab-count">3</span></button>
        <button type="button" role="tab" class="asta-tab" id="ex-tab-c" aria-controls="ex-panel-c" aria-selected="false" tabindex="-1">Settings</button>
      </div>
      <div role="tabpanel" class="asta-tabs-panel" id="ex-panel-a" aria-labelledby="ex-tab-a" tabindex="0">Astabyte is on track for the launch.</div>
      <div role="tabpanel" class="asta-tabs-panel" id="ex-panel-b" aria-labelledby="ex-tab-b" tabindex="0" hidden>Three deploys today.</div>
      <div role="tabpanel" class="asta-tabs-panel" id="ex-panel-c" aria-labelledby="ex-tab-c" tabindex="0" hidden>Project settings.</div>
    </div>

Usage

The demo above, as code.

"use client";

import { Tabs } from "@/components/astabyte/tabs";

const Panel = ({ title, children }: { title: string; children: React.ReactNode }) => (
  <div className="rounded-xl bg-paper-2 p-5">
    <p className="text-[15px] font-medium tracking-[-0.01em] text-ink">{title}</p>
    <p className="mt-1.5 text-[14px] leading-relaxed text-mute">{children}</p>
  </div>
);

export default function TabsDemo() {
  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-lg flex-col gap-10">
        <Tabs
          label="Project"
          tabs={[
            { value: "overview", label: "Overview", content: <Panel title="Overview">Traffic is up 18% this week. Two deploys went out on Tuesday.</Panel> },
            { value: "activity", label: "Activity", count: 12, content: <Panel title="Activity">12 new events since your last visit: comments, deploys and invites.</Panel> },
            { value: "settings", label: "Settings", content: <Panel title="Settings">Domains, environment variables and who can see this project.</Panel> },
            { value: "billing", label: "Billing", content: <Panel title="Billing">You are on Pro. The next invoice is on the 1st.</Panel> },
          ]}
        />
        <Tabs
          variant="pill"
          label="Code"
          defaultValue="npm"
          tabs={[
            { value: "npm", label: "npm", content: <Code>npm install asta-ui</Code> },
            { value: "pnpm", label: "pnpm", content: <Code>pnpm add asta-ui</Code> },
            { value: "bun", label: "bun", content: <Code>bun add asta-ui</Code> },
          ]}
        />
      </div>
    </div>
  );
}

const Code = ({ children }: { children: React.ReactNode }) => (
  <pre className="rounded-lg bg-paper-2 px-4 py-3 font-mono text-[13px] text-ink-2">
    <span className="select-none text-mute">$ </span>
    {children}
  </pre>
);