# TableOfContents (/docs/table-of-contents)





`TableOfContents` lists the headings of a page, indented by level. A thin track runs beside the entries and bends in and out with the nesting. As the page scrolls, the stretch of track beside the sections in view lights up, ending in a dot, and their labels brighten. Clicking an entry scrolls to its heading, below any sticky header, and puts the heading's `#id` in the URL.

```tsx
import { TableOfContents } from "@42-central/ui-react/table-of-contents";

<TableOfContents container="#subject" offset={64} />
```

It is built on [`useScrollSpy`](/docs/hooks/use-scroll-spy), and each entry is an [`Anchor`](/docs/anchor).

## Playground [#playground]

Scroll the subject on the left.

<story.Playground />

## Usage [#usage]

Point `container` at the element that holds the headings, as a ref or a CSS selector. Without it, the whole document is read. `selector` picks which headings count, `h2, h3` by default, so add `h4` for one more level:

```tsx
const article = useRef<HTMLElement>(null);

<article ref={article}>…</article>
<TableOfContents container={article} selector="h2, h3, h4" />
```

The headings are read once, after mount. Each one needs an `id`, since that is what the link points at; [`rehype-slug`](https://github.com/rehypejs/rehype-slug) adds them to Markdown and MDX. A heading without one is skipped, with a warning in development. The component renders nothing until it has found a heading.

If the headings scroll inside an element rather than the window, pass that element as `root`. Every demo on this page works that way, so that it fits its card.

```tsx
const root = useRef<HTMLDivElement>(null);

<div ref={root} className="h-96 overflow-auto">
  <article ref={article}>…</article>
</div>
<TableOfContents container={article} root={root} />
```

## Variants [#variants]

* `track`, the default, draws a hairline that follows the nesting: one level deeper, it bends inward with an S-curve and runs beside the nested entries, then bends back out. The sections in view are the same line drawn in the accent, from the first to the last, ending in a dot. It can span several entries at once.
* `light` slides a tinted pill behind the entry being read.
* `filled` slides a solid pill, for a table of contents that should stand out.

`color` paints the lit range and its dot, or the pill. Without it, they take the text colour.

<Preview align="block" code="&#x22;<TableOfContents container={article} root={root} size=\&#x22;xs\&#x22; withTitle={false} />\n<TableOfContents container={article} root={root} size=\&#x22;xs\&#x22; withTitle={false} variant=\&#x22;light\&#x22; color=\&#x22;brand\&#x22; />\n<TableOfContents container={article} root={root} size=\&#x22;xs\&#x22; withTitle={false} variant=\&#x22;filled\&#x22; color=\&#x22;brand\&#x22; />&#x22;">
  <TableOfContentsVariantsDemo />
</Preview>

The lit range and the pill slide between entries. When the reader prefers reduced motion, they jump instead, and a click scrolls the page instantly instead of smoothly.

## Rich labels [#rich-labels]

A label can be any content: inline [`Code`](/docs/code), or text long enough to wrap onto a second line. The track is measured from the links themselves, and measured again whenever one changes size, so it stays beside the text, wrapped or not.

<Preview align="block" code="&#x22;<TableOfContents\n  data={[\n    { value: \&#x22;tokens\&#x22;, label: \&#x22;Tokens\&#x22;, depth: 2 },\n    { value: \&#x22;loading\&#x22;, label: \&#x22;Loading the fonts\&#x22;, depth: 2 },\n    { value: \&#x22;next\&#x22;, label: <>Next.js — <Code>next/font/google</Code></>, depth: 3 },\n    { value: \&#x22;vite\&#x22;, label: \&#x22;Vite, Remix, plain React — Fontsource\&#x22;, depth: 3 },\n    { value: \&#x22;cdn\&#x22;, label: <>CDN — Google Fonts <Code>{\&#x22;<link>\&#x22;}</Code></>, depth: 3 },\n    { value: \&#x22;self-hosted\&#x22;, label: <>Self-hosted — <Code>@font-face</Code></>, depth: 3 },\n    { value: \&#x22;families\&#x22;, label: \&#x22;Why two families\&#x22;, depth: 2 },\n  ]}\n/>&#x22;">
  <TableOfContentsLabelsDemo />
</Preview>

## Title [#title]

The ready-made component shows an "On this page" title with an icon above the list, and the title names the navigation landmark. `translations.label` changes the text, `icons.title` the icon (`null` for none), and `withTitle={false}` drops the title. The nav is then named by `aria-label` instead.

## Size [#size]

`size`, from `xs` to `xl`, sets the text size, the padding, and how far each level is indented. The default is `sm`.

## Sticky sidebar [#sticky-sidebar]

Put the table of contents in a sticky `aside` next to the content, and set `offset` to the height of anything stuck to the top of the page. A heading counts as being read once it reaches that line, and a click scrolls it to just below it.

The aside sticks inside its nearest scroller. In a page whose window scrolls, that's the page itself; a wrapper with `overflow: auto` or `hidden` between the aside and the window would catch it instead.

<Preview align="block" code="&#x22;<header className=\&#x22;sticky top-0 h-12\&#x22;>libft</header>\n<div className=\&#x22;grid grid-cols-[1fr_11rem] gap-6\&#x22;>\n  <article ref={article}>…</article>\n  <aside className=\&#x22;sticky top-16 self-start\&#x22;>\n    <TableOfContents container={article} offset={48 + 16} color=\&#x22;brand\&#x22; />\n  </aside>\n</div>&#x22;">
  <TableOfContentsStickyDemo />
</Preview>

On a real page the window scrolls, so there's no `root`. Give the aside a `max-height` and `overflow-y: auto`, so that a long table of contents scrolls on its own instead of running off the screen:

```tsx
<aside className="sticky top-16 max-h-[calc(100dvh-4rem)] self-start overflow-y-auto">
  <TableOfContents container="#subject" offset={64} />
</aside>
```

## Entries from data [#entries-from-data]

With `data`, the entries are yours: their labels, their order and their levels. They render on the server too, with no flash on load. Each entry's `value` is the heading's `id`, and `depth` its level. Without `depth`, the level is read from the heading after mount.

<Preview align="block" code="&#x22;<TableOfContents\n  variant=\&#x22;light\&#x22;\n  color=\&#x22;blue\&#x22;\n  data={[\n    { value: \&#x22;introduction\&#x22;, label: \&#x22;1. Introduction\&#x22;, depth: 2 },\n    { value: \&#x22;mandatory-part\&#x22;, label: \&#x22;2. Mandatory part\&#x22;, depth: 2 },\n    { value: \&#x22;libc-functions\&#x22;, label: \&#x22;2.1 Libc\&#x22;, depth: 3 },\n    { value: \&#x22;additional-functions\&#x22;, label: \&#x22;2.2 Additional\&#x22;, depth: 3 },\n    { value: \&#x22;bonus-part\&#x22;, label: \&#x22;3. Bonus\&#x22;, depth: 2 },\n  ]}\n/>&#x22;">
  <TableOfContentsDataDemo />
</Preview>

## Compound API [#compound-api]

For markup of your own, call [`useScrollSpy`](/docs/hooks/use-scroll-spy) and pass what it returns to `TableOfContents.Root` as `spy`. `Item` takes the heading's `id` as `value`, and its children are the label.

<Preview align="block" code="&#x22;const spy = useScrollSpy({ container: article, selector: \&#x22;h2\&#x22; });\n\n<TableOfContents.Root spy={spy} variant=\&#x22;filled\&#x22; color=\&#x22;green\&#x22;>\n  <TableOfContents.Title />\n  <TableOfContents.Indicator />\n  <TableOfContents.List>\n    {spy.data.map((heading, i) => (\n      <TableOfContents.Item key={heading.id} value={heading.id}>\n        <span className=\&#x22;opacity-60\&#x22;>{i + 1}.</span> {heading.label}\n      </TableOfContents.Item>\n    ))}\n  </TableOfContents.List>\n</TableOfContents.Root>&#x22;">
  <TableOfContentsComposedDemo />
</Preview>

Entries render through `Anchor`, so they go through your router's `Link` when the app has a [`LinkComponentProvider`](/docs/hooks/use-link-component). `Item` passes `asChild` and every other prop on to its `Anchor`.

## Right to left [#right-to-left]

The track sits on the inline-start edge, and entries indent from it. In a right-to-left page both move to the right, and the curves mirror. Nothing needs setting: the table of contents follows the `dir` of the page.

## Anatomy [#anatomy]

```tsx
<nav data-scope="table-of-contents" data-part="root" aria-labelledby=":r1:" data-variant="track" data-testid="toc">
  <p data-part="title" id=":r1:"><span aria-hidden="true"><svg /></span>On this page</p>
  <div data-part="indicator" data-variant="track" aria-hidden="true">
    <svg>{/* the quiet track */}</svg>
    <svg>{/* the same path in the accent, clipped to the sections in view */}</svg>
    <span />{/* the dot */}
  </div>
  <ul data-part="list">
    <li data-part="item" data-depth="0" data-active data-visible>
      <a data-part="link" href="#introduction" aria-current="location" data-active data-visible>
        Introduction
      </a>
    </li>
    <li data-part="item" data-depth="1" data-visible>
      <a data-part="link" href="#norm" data-visible>Norm</a>
    </li>
  </ul>
</nav>
```

`data-depth` is the entry's level below the shallowest heading, which sits flush. `data-visible` marks every section in view, the range the track lights; `data-active` and `aria-current` mark only the one being read. With `light` and `filled`, the indicator is a single pill `<div>`. On the compound API, `testId` renders as `data-testid` on each part: the `<nav>`, the title, the `<ul>`, the indicator and, for `Item`, its link. With the `data` prop, give each entry its own `testId`. See [Testing](/docs/testing).

## API [#api]

### TableOfContents [#tableofcontents]

<TypeTable
  type="{
  container: {
    type: &#x22;RefObject<Element | null> | string&#x22;,
    description: &#x22;Where to read the headings from: a ref, or a CSS selector. The whole document without it. Ignored with data.&#x22;,
  },
  selector: {
    type: &#x22;string&#x22;,
    default: '&#x22;h2, h3&#x22;',
    description: &#x22;Which elements count as headings.&#x22;,
  },
  data: {
    type: &#x22;{ value: string; label: ReactNode; depth?: number; testId?: string }[]&#x22;,
    description: &#x22;The entries, instead of reading the page. value is the heading's id. Rendered on the server too.&#x22;,
  },
  root: {
    type: &#x22;RefObject<HTMLElement | null>&#x22;,
    description: &#x22;The element the headings scroll in. The window without it.&#x22;,
  },
  offset: {
    type: &#x22;number&#x22;,
    default: &#x22;0&#x22;,
    description: &#x22;The height in px of whatever is stuck to the top of root, such as a sticky header. A heading is read once it reaches this line, and a click scrolls it to just below.&#x22;,
  },
  getDepth: {
    type: &#x22;(element: HTMLElement) => number&#x22;,
    description: &#x22;A heading's level. By default, its tag's: 3 for an h3.&#x22;,
  },
  variant: {
    type: '&#x22;track&#x22; | &#x22;light&#x22; | &#x22;filled&#x22;',
    default: '&#x22;track&#x22;',
    description: &#x22;track draws a line that follows the nesting and lights the sections in view; light and filled slide a pill behind the entry being read.&#x22;,
  },
  color: {
    type: &#x22;Color&#x22;,
    description: &#x22;The palette of the lit range and its dot, or of the pill. The text colour without it.&#x22;,
  },
  size: {
    type: '&#x22;xs&#x22; | &#x22;sm&#x22; | &#x22;md&#x22; | &#x22;lg&#x22; | &#x22;xl&#x22;',
    default: '&#x22;sm&#x22;',
    description: &#x22;Text size, padding and indent.&#x22;,
  },
  withTitle: {
    type: &#x22;boolean&#x22;,
    default: &#x22;true&#x22;,
    description: &#x22;Shows the title above the list. Without it, the nav is named by aria-label.&#x22;,
  },
  icons: {
    type: &#x22;{ title?: ReactNode }&#x22;,
    description: &#x22;Replaces the icon before the title. null draws none.&#x22;,
  },
  translations: {
    type: &#x22;{ label?: string }&#x22;,
    default: '{ label: &#x22;On this page&#x22; }',
    description: &#x22;The title's text and the navigation landmark's name.&#x22;,
  },
  classNames: {
    type: &#x22;{ title?: string; list?: string; link?: string; indicator?: string }&#x22;,
    description: &#x22;Classes for the title, the list, every entry's link, and the indicator. className goes on the nav.&#x22;,
  },
  testId: {
    type: &#x22;string&#x22;,
    description: &#x22;data-testid on the nav. Each data entry takes its own testId.&#x22;,
  },
}"
/>

### TableOfContents.Root [#tableofcontentsroot]

The `<nav>`. Takes `variant`, `color`, `size`, `icons` and `translations` as above, plus:

<TypeTable
  type="{
  spy: {
    type: &#x22;UseScrollSpyReturnValue&#x22;,
    required: true,
    description: &#x22;What useScrollSpy() returns: the headings and the active one.&#x22;,
  },
  asChild: { type: &#x22;boolean&#x22;, default: &#x22;false&#x22; },
  testId: { type: &#x22;string&#x22; },
}"
/>

### TableOfContents.Item [#tableofcontentsitem]

An `<li>` around an `Anchor`. Every prop other than `value` and `depth` goes to the `Anchor`.

<TypeTable
  type="{
  value: {
    type: &#x22;string&#x22;,
    required: true,
    description: &#x22;The heading's id. The link goes to #value.&#x22;,
  },
  depth: {
    type: &#x22;number&#x22;,
    description: &#x22;The heading's level. Taken from the spy when unset.&#x22;,
  },
  onClick: {
    type: &#x22;(event: MouseEvent) => void&#x22;,
    description: &#x22;Runs before the scroll. Call event.preventDefault() to stop it.&#x22;,
  },
  asChild: { type: &#x22;boolean&#x22;, default: &#x22;false&#x22;, description: &#x22;Renders your link element with the entry's styles and props.&#x22; },
  testId: { type: &#x22;string&#x22;, description: &#x22;data-testid on the link.&#x22; },
}"
/>

`TableOfContents.Title` (a `<p>` with the icon and `translations.label`, or your `children`), `TableOfContents.List` (the `<ul>`) and `TableOfContents.Indicator` take their element's props and a `testId`. A mounted `Title` names the nav through `aria-labelledby`. `Indicator` positions itself against the root, so render it directly inside `Root`, and it doesn't take `asChild`.

## Accessibility [#accessibility]

* The table of contents is a `<nav>` landmark named "On this page" (`translations.label`): by its visible title, or by `aria-label` without one.
* Only the entry being read has `aria-current="location"`, so screen readers announce one current location, even when the track lights several sections. The track, the dot and the pill are decorative (`aria-hidden`).
* Every entry is a real link to `#id`: it's focusable, it follows on Enter, it opens in a new tab with a modifier key, and the hash it puts in the URL can be shared.
* Under `prefers-reduced-motion`, the lit range and the pill jump instead of sliding, and a click scrolls instantly.
* A click moves the scroll, not the focus. After a keyboard click, the next Tab still starts from the entry.
