Component

Table of Contents

Auto-generates a navigable outline from the headings inside a container and highlights the section currently in view using an intersection observer.

Default

Headings are parsed from the referenced container; nested levels are indented automatically.

Introduction

The table of contents derives its entries from the headings inside the container.

Getting started

Install the package and render headings.

Installation

Add it to your dependencies.

Configuration

Tune the selectors to match your markup.

API reference

Every prop, documented.

Installation

$pnpm add @refraction-ui/react-table-of-contents

Usage

tsx
import { useRef } from 'react'
import { TableOfContents } from '@refraction-ui/react'

export function Doc() {
  const containerRef = useRef<HTMLElement | null>(null)

  return (
    <div className="grid grid-cols-[1fr_200px] gap-8">
      <article ref={containerRef}>
        <h2 id="intro">Introduction</h2>
        <h2 id="usage">Usage</h2>
        <h3 id="install">Installation</h3>
      </article>

      <TableOfContents containerRef={containerRef} selectors="h2, h3" />
    </div>
  )
}

Props

Renders nothing when no matching headings are found. Each heading needs an id so the links can anchor to it.

PropTypeDefaultDescription
containerRefReact.RefObject<HTMLElement | null>--Ref to the element whose headings build the list. Falls back to document.body when omitted.
selectorsstring'h2, h3, h4'CSS selectors used to collect headings within the container.
onActiveIdChange(id: string) => void--Called with the id of the heading currently scrolled into view.
classNamestring--Additional CSS classes to apply to the nav element.