Frontend Recipes

Tabs

Compound tabs with a roving tabindex. Only the active tab is in the tab order; the arrow keys move selection — the pattern the ARIA authoring practices describe.

This is the one ARIA pattern in the library that genuinely needs JavaScript, and it is about 40 lines of keyboard handling.

Copy source

Styling

Requires: Nothing. Any bundler that understands .module.css.

This is the component, complete. Copy the files below into a ui/ folder at your project root and keep the folder structure — the imports between them are relative, so the paths have to come along. Each component imports its own .module.css, so its class names are scoped to it and cannot collide with your application's.

ui/components/Tabs/Tabs.tsx
tsx
import {
  createContext,
  useCallback,
  useContext,
  useId,
  useRef,
} from "react";
import { cx } from "../../internal/cx";
import { useControllableState } from "../../internal/useControllableState";
import styles from "./tabs.module.css";

interface TabsContextValue {
  value: string;
  setValue: (next: string) => void;
  baseId: string;
  orientation: "horizontal" | "vertical";
  registerTrigger: (value: string, node: HTMLButtonElement | null) => void;
  triggerRefs: React.RefObject<Map<string, HTMLButtonElement>>;
  order: React.RefObject<string[]>;
}

const TabsContext = createContext<TabsContextValue | null>(null);

function useTabsContext(component: string): TabsContextValue {
  const context = useContext(TabsContext);
  if (!context) {
    throw new Error(`<${component}> must be rendered inside <Tabs>.`);
  }
  return context;
}

export interface TabsProps extends React.HTMLAttributes<HTMLDivElement> {
  value?: string;
  defaultValue: string;
  onValueChange?: (value: string) => void;
  orientation?: "horizontal" | "vertical";
  children: React.ReactNode;
}

// Roving tabindex: only the active tab is in the tab order and the arrow keys
// move selection, as the ARIA authoring practices describe for a tablist.
export function Tabs({
  value,
  defaultValue,
  onValueChange,
  orientation = "horizontal",
  className,
  children,
  ...rest
}: TabsProps): React.JSX.Element {
  const state = useControllableState({
    value,
    defaultValue,
    onChange: onValueChange,
  });
  const baseId = useId();
  const triggerRefs = useRef<Map<string, HTMLButtonElement>>(new Map());
  const order = useRef<string[]>([]);

  const registerTrigger = useCallback(
    (tabValue: string, node: HTMLButtonElement | null) => {
      if (node) {
        triggerRefs.current.set(tabValue, node);
        if (!order.current.includes(tabValue)) order.current.push(tabValue);
      } else {
        triggerRefs.current.delete(tabValue);
        order.current = order.current.filter((entry) => entry !== tabValue);
      }
    },
    [],
  );

  const contextValue: TabsContextValue = {
    value: state.value,
    setValue: state.setValue,
    baseId,
    orientation,
    registerTrigger,
    triggerRefs,
    order,
  };

  return (
    <TabsContext.Provider value={contextValue}>
      <div
        className={cx(
          styles.tabs,
          orientation === "vertical" && styles.vertical,
          className,
        )}
        {...rest}
      >
        {children}
      </div>
    </TabsContext.Provider>
  );
}

export type TabsListProps = React.HTMLAttributes<HTMLDivElement>;

export function TabsList({
  className,
  children,
  onKeyDown,
  ...rest
}: TabsListProps): React.JSX.Element {
  const context = useTabsContext("Tabs.List");
  const isHorizontal = context.orientation === "horizontal";

  const nextKey = isHorizontal ? "ArrowRight" : "ArrowDown";
  const prevKey = isHorizontal ? "ArrowLeft" : "ArrowUp";

  const onListKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(event);
    if (event.defaultPrevented) return;

    const values = context.order.current;
    if (values.length === 0) return;

    const index = values.indexOf(context.value);
    let target: string | undefined;

    switch (event.key) {
      case nextKey:
        target = values[(index + 1) % values.length];
        break;
      case prevKey:
        target = values[(index - 1 + values.length) % values.length];
        break;
      case "Home":
        target = values[0];
        break;
      case "End":
        target = values[values.length - 1];
        break;
      default:
        return;
    }

    if (target === undefined) return;
    event.preventDefault();
    context.setValue(target);
    context.triggerRefs.current.get(target)?.focus();
  };

  return (
    <div
      role="tablist"
      aria-orientation={context.orientation}
      className={cx(styles.list, className)}
      onKeyDown={onListKeyDown}
      {...rest}
    >
      {children}
    </div>
  );
}

export interface TabsTriggerProps
  extends Omit<React.ComponentProps<"button">, "value"> {
  value: string;
  children: React.ReactNode;
  /** Optional count shown as a square counter after the label. */
  count?: number;
}

export function TabsTrigger({
  value,
  count,
  className,
  children,
  onClick,
  disabled,
  ref,
  ...rest
}: TabsTriggerProps): React.JSX.Element {
  const context = useTabsContext("Tabs.Trigger");
  const isSelected = context.value === value;

  const setNode = (node: HTMLButtonElement | null) => {
    context.registerTrigger(value, node);
    if (typeof ref === "function") ref(node);
    else if (ref) ref.current = node;
  };

  return (
    <button
      ref={setNode}
      type="button"
      role="tab"
      id={`${context.baseId}-tab-${value}`}
      aria-selected={isSelected}
      aria-controls={`${context.baseId}-panel-${value}`}
      tabIndex={isSelected ? 0 : -1}
      disabled={disabled}
      className={cx(
        styles.trigger,
        isSelected && styles.triggerSelected,
        className,
      )}
      onClick={(event) => {
        onClick?.(event);
        if (!event.defaultPrevented) context.setValue(value);
      }}
      {...rest}
    >
      <span className={styles.triggerLabel}>{children}</span>
      {count !== undefined ? (
        <span className={styles.count} aria-hidden="true">
          {count}
        </span>
      ) : null}
    </button>
  );
}

export interface TabsPanelProps extends React.HTMLAttributes<HTMLDivElement> {
  value: string;
  /** Keep the panel mounted while hidden, e.g. to preserve form state. */
  keepMounted?: boolean;
}

export function TabsPanel({
  value,
  keepMounted = false,
  className,
  children,
  ...rest
}: TabsPanelProps): React.JSX.Element | null {
  const context = useTabsContext("Tabs.Panel");
  const isSelected = context.value === value;

  if (!isSelected && !keepMounted) return null;

  return (
    <div
      role="tabpanel"
      id={`${context.baseId}-panel-${value}`}
      aria-labelledby={`${context.baseId}-tab-${value}`}
      hidden={!isSelected}
      tabIndex={isSelected ? 0 : -1}
      className={cx(styles.panel, className)}
      {...rest}
    >
      {children}
    </div>
  );
}

Tabs.List = TabsList;
Tabs.Trigger = TabsTrigger;
Tabs.Panel = TabsPanel;
ui/components/Tabs/tabs.module.css
css
/* Tabs — an underlined ruled strip. The active tab is marked by a 2px ink
   bar that sits exactly on the list's bottom rule. */

.tabs {
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.list {
  display: flex;
  align-items: stretch;
  gap: 0;
  border-bottom: var(--fr-rule-width) solid var(--fr-rule-soft);
  overflow-x: auto;
  scrollbar-width: none;
}

.list::-webkit-scrollbar {
  display: none;
}

.vertical {
  flex-direction: row;
  gap: var(--fr-space-5);
}

.vertical > .list {
  flex-direction: column;
  border-bottom: 0;
  border-right: var(--fr-rule-width) solid var(--fr-rule-soft);
  overflow: visible;
  flex: none;
}

.trigger {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: var(--fr-space-2);
  padding: var(--fr-space-3) var(--fr-space-4);
  margin-bottom: -1px;
  background: transparent;
  border: 0;
  border-bottom: 2px solid transparent;
  color: var(--fr-ink-muted);
  font-size: var(--fr-text-small);
  font-weight: var(--fr-weight-semibold);
  letter-spacing: 0.01em;
  cursor: pointer;
  white-space: nowrap;
  transition:
    color var(--fr-duration-fast) var(--fr-ease),
    border-color var(--fr-duration-fast) var(--fr-ease),
    background-color var(--fr-duration-fast) var(--fr-ease);
}

.trigger:hover:not(:disabled) {
  color: var(--fr-ink);
  background: var(--fr-surface-sunken);
}

.trigger:focus-visible {
  outline: var(--fr-focus-width) solid var(--fr-accent);
  outline-offset: calc(var(--fr-focus-offset) * -1);
  z-index: 1;
}

.triggerSelected {
  color: var(--fr-ink);
  border-bottom-color: var(--fr-ink);
}

.trigger:disabled {
  color: var(--fr-disabled-ink);
  cursor: not-allowed;
}

.vertical .trigger {
  justify-content: space-between;
  margin-bottom: 0;
  margin-right: -1px;
  border-bottom: 0;
  border-right: 2px solid transparent;
  text-align: left;
}

.vertical .triggerSelected {
  border-right-color: var(--fr-ink);
  background: var(--fr-surface-sunken);
}

/* A square counter, not a rounded pill. */
.count {
  display: inline-grid;
  place-items: center;
  min-width: 1.25rem;
  height: 1.125rem;
  padding: 0 0.25rem;
  background: var(--fr-surface-sunken);
  border: var(--fr-rule-width) solid var(--fr-rule-soft);
  border-radius: var(--fr-radius);
  font-family: var(--fr-font-mono);
  font-size: 0.625rem;
  font-weight: var(--fr-weight-medium);
  font-variant-numeric: tabular-nums;
  color: var(--fr-ink-muted);
}

.triggerSelected .count {
  background: var(--fr-ink);
  border-color: var(--fr-ink);
  color: var(--fr-paper);
}

.panel {
  padding-top: var(--fr-space-5);
  min-width: 0;
}

.panel:focus-visible {
  outline: var(--fr-focus-width) solid var(--fr-accent);
  outline-offset: var(--fr-space-1);
}

.vertical > .panel {
  padding-top: 0;
}
ui/internal/cx.ts
ts
export type ClassValue = string | false | null | undefined;

// The only part of `clsx` this library needs, without the dependency.
export function cx(...values: ClassValue[]): string {
  const out: string[] = [];
  for (const value of values) {
    if (value) out.push(value);
  }
  return out.join(" ");
}
ui/internal/useControllableState.ts
ts
import { useCallback, useEffect, useRef, useState } from "react";

export interface UseControllableStateOptions<T> {
  value?: T;
  defaultValue: T;
  onChange?: (next: T) => void;
}

export interface ControllableState<T> {
  value: T;
  setValue: (next: T | ((prev: T) => T)) => void;
}

// Two functional updates in one tick both resolve against the committed value,
// so the second wins; pass `value` if you need batched updates.
export function useControllableState<T>({
  value,
  defaultValue,
  onChange,
}: UseControllableStateOptions<T>): ControllableState<T> {
  const isControlled = value !== undefined;
  const [uncontrolled, setUncontrolled] = useState<T>(defaultValue);
  const current = isControlled ? value : uncontrolled;

  const onChangeRef = useRef(onChange);
  // Assigned in an effect, never during render, so `setValue` can stay stable.
  useEffect(() => {
    onChangeRef.current = onChange;
  });

  const setValue = useCallback(
    (next: T | ((prev: T) => T)) => {
      const resolved = isUpdater(next) ? next(current) : next;
      if (Object.is(resolved, current)) return;
      if (!isControlled) setUncontrolled(resolved);
      onChangeRef.current?.(resolved);
    },
    [current, isControlled],
  );

  return { value: current, setValue };
}

// `typeof x === "function"` does not narrow a union that includes `T` when `T`
// could itself be callable, so the guard states that case and leaves the rest.
function isUpdater<T>(value: T | ((prev: T) => T)): value is (prev: T) => T {
  return typeof value === "function";
}

Every component reads from these two files. Copy them once, on your first component, and reuse them thereafter.

ui/styles/tokens.css
css
/* Every ground is white and every value below cleared AA on it; dark mode
   re-derives rather than inverting. Check contrast again before changing a value. */

:root {
  /* The only radius token. Do not override per component. */
  --fr-radius: 0px;

  /* Core surfaces — flat by default; separation comes from rules, not fills. */
  --fr-paper: #ffffff;
  --fr-surface: #ffffff;
  --fr-surface-sunken: #f5f5f5;
  --fr-ink: #262626;
  --fr-ink-muted: #525252;
  --fr-ink-subtle: #737373;

  /* Rules — soft divides, rule bounds, strong marks a control edge. A boundary
     is a hairline tone; only controls and active markers earn the ink one. */
  --fr-rule: #e5e5e5;
  --fr-rule-strong: #262626;
  --fr-rule-soft: #ededed;

  /* Accent: Emerald. Reserved for interaction, never decoration. `bright` is
     ornament only — marks and arrows, never a label or a fill that carries one. */
  --fr-accent: #047857;
  --fr-accent-ink: #ffffff;
  --fr-accent-soft: #ecfdf5;
  --fr-accent-hover: #065f46;
  --fr-accent-bright: #10b981;

  /* Status. Success stays a true green rather than a second emerald, so a badge
     tone never reads as the accent. */
  --fr-danger: #a81f24;
  --fr-danger-soft: #fbeaeb;
  --fr-danger-ink: #ffffff;
  --fr-success: #15803d;
  --fr-success-soft: #f0fdf4;
  --fr-success-ink: #ffffff;
  --fr-warning: #7a5312;
  --fr-warning-soft: #f8efdf;
  --fr-warning-ink: #ffffff;

  /* Inverse surfaces */
  --fr-inverse-surface: #262626;
  --fr-inverse-ink: #ffffff;

  /* Disabled */
  --fr-disabled-surface: #f0f0f0;
  --fr-disabled-ink: #737373;

  /* Hard shadow: no blur, ever. */
  --fr-shadow-hard: 3px 3px 0 var(--fr-rule-strong);
  --fr-shadow-hard-sm: 2px 2px 0 var(--fr-rule-strong);

  /* No font ships with the library, so this is the platform's own UI face. */
  --fr-font-sans: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue",
    Arial, sans-serif;
  --fr-font-mono: ui-monospace, "SF Mono", "Menlo", "Consolas", monospace;

  --fr-text-display: 3.5rem;
  --fr-text-h1: 2.5rem;
  --fr-text-h2: 1.75rem;
  --fr-text-h3: 1.25rem;
  --fr-text-body: 0.9375rem;
  --fr-text-small: 0.8125rem;
  --fr-text-micro: 0.6875rem;

  --fr-leading-display: 1.02;
  --fr-leading-heading: 1.15;
  --fr-leading-body: 1.6;
  --fr-tracking-micro: 0.08em;
  --fr-tracking-display: -0.02em;

  --fr-weight-regular: 400;
  --fr-weight-medium: 500;
  --fr-weight-semibold: 600;
  --fr-weight-bold: 700;

  /* Spacing scale — 4px base */
  --fr-space-0: 0;
  --fr-space-1: 0.25rem;
  --fr-space-2: 0.5rem;
  --fr-space-3: 0.75rem;
  --fr-space-4: 1rem;
  --fr-space-5: 1.5rem;
  --fr-space-6: 2rem;
  --fr-space-7: 3rem;
  --fr-space-8: 4rem;
  --fr-space-9: 6rem;

  /* Sizing */
  --fr-control-sm: 1.75rem;
  --fr-control-md: 2.25rem;
  --fr-control-lg: 2.75rem;
  --fr-rule-width: 1px;
  --fr-rule-width-strong: 2px;
  --fr-focus-width: 2px;
  --fr-focus-offset: 2px;

  /* Motion — short and linear; this library does not bounce. */
  --fr-duration-fast: 90ms;
  --fr-duration-base: 140ms;
  --fr-ease: cubic-bezier(0.2, 0, 0, 1);

  /* Layers */
  --fr-z-sticky: 10;
  --fr-z-overlay: 100;
  --fr-z-dialog: 101;

  /* Layout */
  --fr-container: 78rem;
  --fr-measure: 68ch;
}

/* Dark re-derives rather than inverting: the ground stays near-black and the
   accent lifts so it still clears AA (#34D399 on #0A0A0A is 10.33:1). */
[data-theme="dark"] {
  --fr-paper: #0a0a0a;
  --fr-surface: #141414;
  --fr-surface-sunken: #1c1c1c;
  --fr-ink: #f5f5f5;
  --fr-ink-muted: #a3a3a3;
  --fr-ink-subtle: #7a7a7a;

  --fr-rule: #3a3a3a;
  --fr-rule-strong: #f5f5f5;
  --fr-rule-soft: #2a2a2a;

  --fr-accent: #34d399;
  --fr-accent-ink: #022c22;
  --fr-accent-soft: #052e22;
  --fr-accent-hover: #6ee7b7;
  --fr-accent-bright: #34d399;

  --fr-danger: #fca5a5;
  --fr-danger-soft: #2e1214;
  --fr-danger-ink: #240708;
  --fr-success: #86efac;
  --fr-success-soft: #0d2415;
  --fr-success-ink: #04150c;
  --fr-warning: #e2b262;
  --fr-warning-soft: #2a2011;
  --fr-warning-ink: #1c1305;

  --fr-inverse-surface: #f5f5f5;
  --fr-inverse-ink: #0a0a0a;

  --fr-disabled-surface: #1f1f1f;
  --fr-disabled-ink: #6a6a6a;

  --fr-shadow-hard: 3px 3px 0 #f5f5f5;
  --fr-shadow-hard-sm: 2px 2px 0 #f5f5f5;
}

/* Opt-in inverse region: use for a closing band or a deliberate contrast strip. */
[data-theme="inverse"] {
  --fr-paper: #171717;
  --fr-surface: #171717;
  --fr-surface-sunken: #242424;
  --fr-ink: #ffffff;
  --fr-ink-muted: #b5b5b5;
  --fr-ink-subtle: #8a8a8a;
  --fr-rule: #3d3d3d;
  --fr-rule-strong: #ffffff;
  --fr-rule-soft: #2e2e2e;
  --fr-accent: #34d399;
  --fr-accent-ink: #022c22;
  --fr-accent-soft: #052e22;
  --fr-accent-hover: #6ee7b7;
  --fr-accent-bright: #34d399;
  --fr-inverse-surface: #ffffff;
  --fr-inverse-ink: #171717;
  --fr-shadow-hard: 3px 3px 0 #ffffff;
  --fr-shadow-hard-sm: 2px 2px 0 #ffffff;
}

@media (prefers-reduced-motion: reduce) {
  :root {
    --fr-duration-fast: 0ms;
    --fr-duration-base: 0ms;
  }
}
ui/styles/base.css
css
/* Only what a module cannot scope: the page reset. Everything a component owns
   lives in its .module.css, so no global class here can collide with yours. */

*,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  -webkit-text-size-adjust: 100%;
  text-size-adjust: 100%;
}

body {
  margin: 0;
  font-family: var(--fr-font-sans);
  font-size: var(--fr-text-body);
  line-height: var(--fr-leading-body);
  color: var(--fr-ink);
  background: var(--fr-paper);
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

h1,
h2,
h3,
h4,
h5,
h6,
p,
figure,
blockquote,
dl,
dd {
  margin: 0;
}

ul,
ol {
  margin: 0;
  padding: 0;
}

h1,
h2,
h3,
h4,
h5,
h6 {
  font-weight: var(--fr-weight-semibold);
  line-height: var(--fr-leading-heading);
  letter-spacing: -0.02em;
  text-wrap: balance;
}

a {
  color: var(--fr-accent);
  text-decoration-thickness: 1px;
  text-underline-offset: 2px;
}

a:hover {
  color: var(--fr-accent-hover);
}

img,
svg,
video,
canvas {
  display: block;
  max-width: 100%;
}

button,
input,
select,
textarea {
  font: inherit;
  color: inherit;
  letter-spacing: inherit;
}

Then import the component from its file. A page that holds state needs "use client".

css
/* app/layout.tsx — once, before your own CSS */
import "../ui/styles/tokens.css";
import "../ui/styles/base.css";
tsx
// app/page.tsx
"use client";

import { Tabs, TabsList, TabsTrigger, TabsPanel } from "../ui/components/Tabs/Tabs";

Basic

A tablist with panels

The overview panel. Only the selected panel is in the DOM.

Try it with the keyboard: focus a tab, then press Left and Right. Selection follows focus, and Home and End jump to the first and last tab.

Only the active panel is in the DOM. Pass keepMounted to a panel if it holds state that must survive a switch.

With counts

A square counter per tab

24 issues.

The counter is a square with a 1px rule, not a rounded pill, and it is aria-hidden — the count is decorative in the tab context, and announcing "open, seven, tab" slows the tablist down.

Vertical

Vertical orientation

General settings. Arrow keys move down this list.

In vertical mode the arrow keys move up and down, and the active marker becomes a right-hand rule rather than an underline.

Controlled

Selection driven from outside

Panel one.

Selected: one

defaultValue is required even when controlled — it types the value as a string and provides the initial value for the uncontrolled case. Passing both is normal here.

Props

Tabs

PropTypeDefaultDescription
defaultValue*string—Initial selected tab. Required even when controlled.
valuestring—Controlled selected value.
onValueChange(value: string) => void—Called when the selection changes.
orientation'horizontal' | 'vertical'horizontalDetermines which arrow keys move selection.
Tabs props

Tabs.Trigger

PropTypeDefaultDescription
value*string—Identifies the tab and matches its panel.
countnumber—Renders a square counter after the label.
disabledboolean—Removes the tab from the roving order and blocks selection.
Tabs.Trigger props

Tabs.Panel

PropTypeDefaultDescription
value*string—Matches the trigger's value.
keepMountedbooleanfalseKeeps the panel in the DOM while hidden.
Tabs.Panel props

Accessibility

The full ARIA tabs contract, implemented rather than approximated:

  • role="tablist" on Tabs.List, with aria-orientation.
  • role="tab" with aria-selected, aria-controls, and id.
  • role="tabpanel" with aria-labelledby pointing back at its tab.
  • Roving tabindex: the selected tab is tabIndex={0}, the rest are -1.
  • Arrow keys move selection and focus together, wrapping at both ends.
  • Home and End jump to the first and last tab.
  • A hidden panel is hidden and tabIndex={-1}, so it is not reachable while inactive.
  • Using a trigger outside Tabs throws a clear error at render rather than silently doing nothing.

Do and don't

DoUse tabs for sibling views of the same object.
Don’tUse tabs for sequential steps. That is a stepper, and it needs different semantics.
DoKeep the label to one or two words.
Don’tPut a tablist inside a tab panel. It is almost always a layout problem.