markdown-toc.tsx

Overview

markdown-toc.tsx is a React functional component designed to dynamically generate and display a Table of Contents (ToC) for markdown content rendered on a webpage. It scans the document for headings (<h2> and <h3>) within markdown content and organizes them hierarchically. The ToC allows users to quickly navigate to different sections of the markdown by clicking on the generated anchor links.

This component uses Ant Design's Anchor component to render the ToC with smooth scrolling and link highlighting features. The ToC is displayed as a fixed-position sidebar on the right side of the viewport, providing persistent navigation while the user scrolls through the content.


Detailed Documentation

Imports


Interface: MarkdownTocProps

interface MarkdownTocProps {
  content: string;
}

Component: MarkdownToc

const MarkdownToc: React.FC<MarkdownTocProps> = ({ content }) => { ... }

Internal Function: generateTocItems


React Hook: useEffect


JSX Render

<div className="markdown-toc ...style props">
  <Anchor items={items} affix={false} />
</div>

Usage Example

import React from 'react';
import MarkdownToc from './markdown-toc';

// Assume markdown content is rendered somewhere with class "wmde-markdown"
const markdownContent = `
## Section 1
### Subsection 1.1
## Section 2
### Subsection 2.1
`;

const Page = () => (
  <div>
    <div className="wmde-markdown" dangerouslySetInnerHTML={{ __html: markdownToHtml(markdownContent) }} />
    <MarkdownToc content={markdownContent} />
  </div>
);

Implementation Details and Notes


Interaction With Other Parts of the System


Visual Diagram

componentDiagram
    direction LR
    MarkdownToc <|-- React.FC
    MarkdownToc : +content: string
    MarkdownToc : +items: AnchorLinkItemProps[]
    MarkdownToc : +generateTocItems()
    MarkdownToc --> Anchor : renders with items
    MarkdownToc ..> document.querySelectorAll : queries headings h2, h3 in .wmde-markdown
    Anchor : Displays ToC links

Summary

markdown-toc.tsx provides a reusable React component that dynamically builds a hierarchical Table of Contents for markdown content based on <h2> and <h3> headings. It leverages direct DOM access to detect headings and Ant Design's Anchor component to render the ToC with smooth navigation. This component improves user experience by offering quick section navigation, especially in long markdown documents. It integrates tightly with markdown renderers that produce HTML with consistent heading IDs inside an element with class .wmde-markdown.