Skip to main content
react-md

useTableOfContentsHeadings

function useTableOfContentsHeadings(
  options: TableOfContentsHeadingsOptions = {}
): readonly HeadingReferenceWithChildren[];

The useTableOfContentsHeadings should normally be used with the useActiveHeadingId hook to generate a table of contents for the current page.

Example Usage

import { useActiveHeadingId } from "@react-md/core/navigation/useActiveHeadingId";
import { useTableOfContentsHeadings } from "@react-md/core/navigation/useTableOfContentsHeadings";

function Example() {
  const headings = useTableOfContentsHeadings();
  const activeHeadingId = useActiveHeadingId({ headings });

  return (
    <TableOfContents headings={headings} activeHeadingId={activeHeadingId} />
  );
}

Parameters

export interface TableOfContentsHeadingsOptions {
  /**
   * This should be a `document.querySelectorAll` query that returns elements
   * to display in a table of contents component that have a valid id.
   *
   * @see {@link DEFAULT_HEADING_SELECTOR}
   * @defaultValue `main :where(:not(nav *)):where(h1[id],h2[id],h3[id],h4[id],h5[id],h6[id])`
   */
  selector?: string;

  /**
   * @see {@link DEFAULT_GET_HEADING_DEPTH}
   * @defaultValue `(element) => parseInt(element.tagName.substring(1))`
   */
  getDepth?: (element: Element) => number;
}

Returns

A readonly HeadingReferenceWithChildren[]

/**
 * @since 6.0.0
 */
export interface HeadingReference {
  id: string;
}

/**
 * @since 6.0.0
 */
export interface HeadingReferenceWithChildren extends HeadingReference {
  children?: readonly HeadingReferenceWithChildren[];
}

The id for the heading that is currently "active" by having content mostly visible within the viewport.

See Also