Skip to content
shadcn.io

shadcn.io is not affiliated with official shadcn/ui

Shadcn Table of Contents for React and Tailwind

Highlights the heading in view on docs and long pages.

Introduction

Getting Started

Installation

Usage

Conclusion

Installation

bunx --bun shadcn@latest add https://kit.dev/r/toc.json

Anatomy

Table of Contents anatomy: root, title, indicator, item, link

Usage

import { useCallback, useRef } from "react";
import {
  Toc,
  TocContent,
  TocIndicator,
  TocItem,
  TocLink,
  TocList,
  TocNav,
  TocTitle,
} from "@/components/ui/toc";
interface Item {
  depth: number;
  label: string;
  lines: number;
  value: string;
}

const items: Item[] = [
  {
    depth: 2,
    label: "Introduction",
    lines: 8,
    value: "toc-basic-introduction",
  },
  {
    depth: 2,
    label: "Getting Started",
    lines: 7,
    value: "toc-basic-getting-started",
  },
  {
    depth: 2,
    label: "Installation",
    lines: 6,
    value: "toc-basic-installation",
  },
  { depth: 2, label: "Usage", lines: 9, value: "toc-basic-usage" },
  { depth: 2, label: "Conclusion", lines: 7, value: "toc-basic-conclusion" },
];

const TocDemo = () => {
  const contentRef = useRef<HTMLElement | null>(null);
  const getScrollEl = useCallback(() => contentRef.current, []);

  return (
    <Toc className="max-w-2xl" items={items} scrollEl={getScrollEl}>
      <TocContent className="h-80 pe-2" ref={contentRef}>
        {items.map((item) => (
          <section
            className="not-first:mt-12 flex flex-col gap-3"
            key={item.value}
          >
            <h2
              className="scroll-mt-4 font-heading font-semibold text-lg"
              id={item.value}
            >
              {item.label}
            </h2>
            <div
              className="rounded-md bg-muted"
              style={{ height: `${item.lines * 0.75}rem` }}
            />
          </section>
        ))}
      </TocContent>

      <TocNav scrollToTop>
        <TocTitle>On this page</TocTitle>
        <TocList>
          <TocIndicator />
          {items.map((item) => (
            <TocItem item={item} key={item.value}>
              <TocLink href={`#${item.value}`}>{item.label}</TocLink>
            </TocItem>
          ))}
        </TocList>
      </TocNav>
    </Toc>
  );
};

Demos

Nested

Root Provider

With Collapsible

With Hover

With Indicator

With Rail

With Select

With Tree View

API Reference

Toc

div

PropType
AttributeType
CSS variableType

TocTitle

h2

PropType
AttributeType

TocList

ul

PropType
AttributeType

TocItem

li

PropType
AttributeType
CSS variableType

a

PropType
AttributeType

TocIndicator

div

PropType
AttributeType
CSS variableType

TocContent

article

PropType
AttributeType

TocNav

nav

PropType
AttributeType

TocScrollToTop

PropType
AttributeType

TocRootProvider

div

PropType
AttributeType
CSS variableType

useToc

PropType

TocContext

PropType