Skip to content

ScrollSpy

Navigation

Section navigation that follows a bounded, independently scrollable guide.

Launch guideActive section linksKeyboard scroll regionEmpty state
Open preview

Responsive viewport — resize the window to explore. Direction and density apply only to this preview. Theme applies to the docs too.

Usage

Provide unique section ids, titles, and content. This component owns a scroll region; it tracks sections inside that region rather than the whole document. Section links scroll and focus the matching section without changing the page URL. The final section becomes active at the bottom. A bounded pane makes this suitable for embedded guides, inspectors, and documentation previews.

Import
import { ScrollSpy } from "@/components/ui/scroll-spy";

Shipped as editable source in src/components/ui/scroll-spy.tsx in both apps. Copy the implementation below when moving it to another project. Copy the complete example from Source code for all imports and state. Add "use client" when using hooks or event handlers. See installation and theming for project setup.

Component source

The complete implementation is included in both apps. It uses the React, Radix, Lucide, and shared-core dependencies already installed in Apex. Keep your project’s semantic theme tokens when reusing it.

src/components/ui/scroll-spy.tsx
"use client";
import { useId, useRef, useState, type ReactNode } from "react";
import { cn } from "@dashboardpack/core/lib/utils";
export interface ScrollSpySection {
  id: string;
  title: string;
  content: ReactNode;
}
export interface ScrollSpyProps {
  label: string;
  sections: ScrollSpySection[];
  height?: number;
  className?: string;
}
export function ScrollSpy({
  label,
  sections,
  height = 320,
  className,
}: ScrollSpyProps) {
  const prefix = useId();
  const root = useRef<HTMLDivElement>(null);
  const [active, setActive] = useState<string | undefined>(sections[0]?.id);
  const selected = sections.some((section) => section.id === active)
    ? active
    : sections[0]?.id;
  const update = () => {
    const container = root.current;
    if (!container) return;
    const top = container.getBoundingClientRect().top;
    let next: string | undefined = sections[0]?.id;
    for (const element of container.querySelectorAll<HTMLElement>(
      "[data-spy-section]",
    )) {
      if (element.getBoundingClientRect().top - top <= 32)
        next = element.dataset.spySection;
    }
    if (
      container.scrollTop + container.clientHeight >=
      container.scrollHeight - 2
    )
      next = sections.at(-1)?.id;
    setActive(next);
  };
  return (
    <div className={cn("min-w-0 space-y-3", className)}>
      <nav
        aria-label={label}
        className="flex flex-wrap gap-1 rounded-lg border bg-muted/30 p-1"
      >
        {sections.map((section) => (
          <a
            key={section.id}
            href={`#${prefix}-${section.id}`}
            aria-current={selected === section.id ? "location" : undefined}
            onClick={(event) => {
              event.preventDefault();
              const element = document.getElementById(
                `${prefix}-${section.id}`,
              );
              const container = root.current;
              if (!element || !container) return;
              container.scrollTo({
                top:
                  container.scrollTop +
                  element.getBoundingClientRect().top -
                  container.getBoundingClientRect().top -
                  16,
                behavior: matchMedia("(prefers-reduced-motion: reduce)").matches
                  ? "instant"
                  : "smooth",
              });
              element.focus({ preventScroll: true });
            }}
            className={cn(
              "rounded-md px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",
              selected === section.id
                ? "bg-background font-medium shadow-xs"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            {section.title}
          </a>
        ))}
      </nav>
      <div
        ref={root}
        role="region"
        aria-label={`${label} content`}
        tabIndex={0}
        onScroll={update}
        style={{
          height: Math.max(120, Number.isFinite(height) ? height : 320),
        }}
        className="overflow-y-auto rounded-xl border bg-card p-5 outline-none focus-visible:ring-2 focus-visible:ring-ring"
      >
        {sections.length ? (
          sections.map((section) => (
            <section
              key={section.id}
              id={`${prefix}-${section.id}`}
              data-spy-section={section.id}
              tabIndex={-1}
              aria-labelledby={`${prefix}-${section.id}-title`}
              className="min-h-64 space-y-4 pb-10 outline-none"
            >
              <h3
                id={`${prefix}-${section.id}-title`}
                className="text-base font-semibold"
              >
                {section.title}
              </h3>
              <div className="text-sm leading-7 text-muted-foreground">
                {section.content}
              </div>
            </section>
          ))
        ) : (
          <p className="text-sm text-muted-foreground">
            No sections available.
          </p>
        )}
      </div>
    </div>
  );
}

API reference

Common props and defaults. Slot-specific props are named below; native elements also accept their standard HTML attributes. The component TypeScript definitions are the complete type reference.

ScrollSpy props
PropType / DefaultDescription
labelstring

Default: required

Accessible name for navigation and its content region.
sectionsScrollSpySection[]

Default: required

Unique id, title, and ReactNode content in document order.
heightnumber

Default: 320

Pane height in pixels; clamped to at least 120.
classNamestring

Default: —

Extend the component container with theme-aware utility classes.

Build with these too