getToc(options)

Get only the table of contents from an MDX file. This is useful for building navigation sidebars or TOC components.

Usage

import { getToc } from "@ariadocs/react";

const toc = await getToc({
  contentDir: "contents/docs",
  slug: "getting-started",
});

Parameters

options

PropertyTypeRequiredDescription
contentDirstringYesPath to the content directory
slugstringYesFile path without .mdx extension

Returns

Returns an array of TocItem objects:

PropertyTypeDescription
idstringHeading ID (for anchor links)
valuestringHeading text content
depthnumberHeading level (1-6)
itemsTocItem[]Nested child items (optional)

Example

import { getToc } from "@ariadocs/react";

export default async function TableOfContents({
  params,
}: {
  params: { slug: string };
}) {
  const toc = await getToc({
    contentDir: "contents/docs",
    slug: params.slug,
  });

  return (
    <nav>
      <h2>On this page</h2>
      <ul>
        {toc.map((item) => (
          <li key={item.id}>
            <a href={`#${item.id}`}>{item.value}</a>
            {item.items && item.items.length > 0 && (
              <ul>
                {item.items.map((child) => (
                  <li key={child.id}>
                    <a href={`#${child.id}`}>{child.value}</a>
                  </li>
                ))}
              </ul>
            )}
          </li>
        ))}
      </ul>
    </nav>
  );
}

Recursive TOC Component

For deeply nested headings, use a recursive component:

function TocList({ items }: { items: TocItem[] }) {
  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>
          <a href={`#${item.id}`}>{item.value}</a>
          {item.items && item.items.length > 0 && (
            <TocList items={item.items} />
          )}
        </li>
      ))}
    </ul>
  );
}

Use Cases

  • Building table of contents sidebars
  • Creating "on this page" navigation
  • Generating outline views
  • Building scroll spy navigation