Underline tabs
Accessible tabs with an underline that slides to the selected tab. Follows the ARIA tabs pattern with roving focus (arrow keys, Home and End), automatic or manual activation, linked tab and panel ids, disabled tabs and optional count badges. The tab row scrolls sideways on narrow screens and keeps the selected tab in view; the slide respects reduced motion.
Source
"use client";
import {
createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState,
type ButtonHTMLAttributes, type HTMLAttributes, type KeyboardEvent, type ReactNode,
} from "react";
import { cn } from "@/lib/utils";
interface TabsContextValue {
value: string;
select: (value: string) => void;
activation: "automatic" | "manual";
idFor: (kind: "tab" | "panel", value: string) => string;
}
const TabsContext = createContext<TabsContextValue | null>(null);
function useTabs(component: string) {
const context = useContext(TabsContext);
if (!context) throw new Error(`<${component}> must be used inside <Tabs>.`);
return context;
}
export interface TabsProps extends Omit<HTMLAttributes<HTMLDivElement>, "defaultValue" | "onChange"> {
value?: string;
defaultValue: string;
onValueChange?: (value: string) => void;
/** "automatic" selects a tab as soon as it is focused with the arrow keys; "manual" waits for Enter or Space. */
activationMode?: "automatic" | "manual";
}
export function Tabs({ value: controlled, defaultValue, onValueChange, activationMode = "automatic", className, children, ...props }: TabsProps) {
const id = useId();
const [uncontrolled, setUncontrolled] = useState(defaultValue);
const value = controlled ?? uncontrolled;
const select = (next: string) => {
if (next === value) return;
if (controlled === undefined) setUncontrolled(next);
onValueChange?.(next);
};
const idFor = (kind: "tab" | "panel", tab: string) => `${id}-${kind}-${tab.replace(/[^\w-]/g, "_")}`;
return (
<TabsContext.Provider value={{ value, select, activation: activationMode, idFor }}>
<div className={cn("flex flex-col", className)} {...props}>{children}</div>
</TabsContext.Provider>
);
}
export interface TabsListProps extends HTMLAttributes<HTMLDivElement> {
/** Name the tab set for screen readers, unless a heading labels it through aria-labelledby. */
"aria-label"?: string;
}
export function TabsList({ className, children, onKeyDown, ...props }: TabsListProps) {
const { value, select, activation } = useTabs("TabsList");
const listRef = useRef<HTMLDivElement>(null);
const [indicator, setIndicator] = useState<{ left: number; width: number } | null>(null);
const [animate, setAnimate] = useState(false);
const userChanged = useRef(false);
// Measure the selected tab; re-measure when the list resizes (fonts, window, counts).
useLayoutEffect(() => {
const list = listRef.current;
if (!list) return;
const measure = () => {
const tab = list.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]');
if (!tab) return setIndicator(null);
const label = tab.querySelector<HTMLElement>("[data-tab-label]") ?? tab;
setIndicator({ left: tab.offsetLeft + label.offsetLeft, width: label.offsetWidth });
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(list);
list.querySelectorAll('[role="tab"]').forEach((tab) => observer.observe(tab));
return () => observer.disconnect();
}, [value]);
// Slide only after the first placement, so the indicator does not sweep in from the left on load.
useEffect(() => {
if (!indicator || animate) return;
const frame = requestAnimationFrame(() => setAnimate(true));
return () => cancelAnimationFrame(frame);
}, [indicator, animate]);
// When the user changes tabs, bring the new one into view inside the scrolling list (never scrolls the page).
useEffect(() => {
const list = listRef.current;
const tab = list?.querySelector<HTMLElement>('[role="tab"][aria-selected="true"]');
if (!list || !tab || !userChanged.current) return;
userChanged.current = false;
if (tab.offsetLeft < list.scrollLeft) list.scrollLeft = tab.offsetLeft - 8;
else if (tab.offsetLeft + tab.offsetWidth > list.scrollLeft + list.clientWidth)
list.scrollLeft = tab.offsetLeft + tab.offsetWidth - list.clientWidth + 8;
}, [value]);
function handleKeyDown(event: KeyboardEvent<HTMLDivElement>) {
onKeyDown?.(event);
if (event.defaultPrevented) return;
const tabs = Array.from(listRef.current?.querySelectorAll<HTMLButtonElement>('[role="tab"]:not([disabled])') ?? []);
const index = tabs.indexOf(document.activeElement as HTMLButtonElement);
if (index < 0) return;
const keys: Record<string, number> = { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: tabs.length - 1 };
if (!(event.key in keys)) return;
event.preventDefault();
const next = tabs[(keys[event.key] + tabs.length) % tabs.length];
next.focus();
if (activation === "automatic" && next.dataset.value) {
userChanged.current = true;
select(next.dataset.value);
}
}
return (
<div
ref={listRef}
role="tablist"
aria-orientation="horizontal"
onKeyDown={handleKeyDown}
onClickCapture={() => (userChanged.current = true)}
className={cn(
"relative flex shrink-0 items-stretch gap-1 overflow-x-auto overflow-y-hidden shadow-[inset_0_-1px_0_var(--border)]",
"[scrollbar-width:none] [&::-webkit-scrollbar]:hidden",
className,
)}
{...props}
>
{children}
<span
aria-hidden="true"
className={cn(
"pointer-events-none absolute bottom-0 left-0 h-0.5 rounded-full bg-foreground",
animate && "motion-safe:transition-[translate,width] motion-safe:duration-300 motion-safe:ease-[cubic-bezier(.3,.8,.3,1)]",
!indicator && "opacity-0",
)}
style={indicator ? { width: indicator.width, translate: `${indicator.left}px 0` } : undefined}
/>
</div>
);
}
export interface TabsTriggerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "value"> {
value: string;
/** A small count after the label, such as unread items. */
count?: ReactNode;
}
export function TabsTrigger({ value, count, disabled, className, children, onClick, ...props }: TabsTriggerProps) {
const { value: selectedValue, select, idFor } = useTabs("TabsTrigger");
const selected = value === selectedValue;
return (
<button
type="button"
role="tab"
id={idFor("tab", value)}
aria-selected={selected}
aria-controls={idFor("panel", value)}
tabIndex={selected ? 0 : -1}
disabled={disabled}
data-value={value}
data-state={selected ? "active" : "inactive"}
onClick={(event) => {
onClick?.(event);
if (!event.defaultPrevented) select(value);
}}
className={cn(
"group/tab relative flex shrink-0 items-center pb-2 pt-1 text-sm font-medium outline-hidden",
"text-muted-foreground transition-colors duration-150 hover:text-foreground aria-selected:text-foreground",
"disabled:pointer-events-none disabled:opacity-45",
className,
)}
{...props}
>
<span
data-tab-label
className={cn(
"flex h-8 items-center gap-2 whitespace-nowrap rounded-md px-2.5 transition-colors",
"group-hover/tab:bg-accent/70 group-focus-visible/tab:ring-[3px] group-focus-visible/tab:ring-ring/50 [&_svg]:size-4 [&_svg]:shrink-0",
)}
>
{children}
{count !== undefined && (
<span
className={cn(
"min-w-5 rounded-full px-1.5 text-center text-[11px] font-medium leading-[18px] tabular-nums",
selected ? "bg-foreground text-background" : "bg-muted text-muted-foreground",
)}
>
{count}
</span>
)}
</span>
</button>
);
}
export interface TabsPanelProps extends HTMLAttributes<HTMLDivElement> {
value: string;
}
export function TabsPanel({ value, className, children, ...props }: TabsPanelProps) {
const { value: selectedValue, idFor } = useTabs("TabsPanel");
const selected = value === selectedValue;
return (
<div
role="tabpanel"
id={idFor("panel", value)}
aria-labelledby={idFor("tab", value)}
tabIndex={0}
hidden={!selected}
className={cn("rounded-md outline-hidden focus-visible:ring-[3px] focus-visible:ring-ring/50", className)}
{...props}
>
{selected && children}
</div>
);
}
