Get Node TOC
Returns the table of contents for a page node.
Returns an array of TocItem for the given slug, parsed from the headings in the MDX file. Returns an empty array if the node is not found.
import { getNodeToc } from 'slugtree'
const toc = getNodeToc(['guides', 'routing'])Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
slug | string | string[] | [] | Slug of the page node. |
Return value
Returns TocItem[]. Each item represents one heading in the document:
interface TocItem {
id: string // heading anchor id
text: string // heading text
depth: number // 1 = h1, 2 = h2, 3 = h3, etc.
}Returns an empty array when the node is not found or has no headings.
Usage
Typical usage in a right sidebar table of contents panel:
import { getNodeToc } from 'slugtree'
export default function TableOfContents({ slug }: { slug: string[] }) {
const toc = getNodeToc(slug)
if (toc.length === 0) return null
return (
<ul>
{toc.map((item) => (
<li key={item.id} style={{ paddingLeft: `${(item.depth - 1) * 12}px` }}>
<a href={`#${item.id}`}>{item.text}</a>
</li>
))}
</ul>
)
}For client components, use useNodeToc() from slugtree/react.