zhangyu1818 / react-markdown-toc

Generating a Table of Contents (TOC) from Markdown.
https://zhangyu1818.github.io/react-markdown-toc/
MIT License
2 stars 0 forks source link
markdown-toc react react-markdown react-markdown-toc toc

react-markdown-toc

react-markdown-toc is a library designed for React applications, focused on generating a Table of Contents (TOC) from Markdown text.

Preview Link

Features

Installation

You can install react-markdown-toc using the following commands:

npm install react-markdown-toc

Usage

fromMarkdown

The fromMarkdown function is used to generate a TOC tree from a Markdown text.

Example Usage:

import { fromMarkdown } from 'react-markdown-toc'

const [result, map] = fromMarkdown(`## Heading 1\n\n### Heading 1.1\n\n## Heading 2`)

The fromMarkdown function returns a tuple containing the TOC tree and a map linking IDs to keys within the tree.

Server Component

The server component does not support custom rendering functions; it renders the ul, li, and a tags in a fixed manner.

Example Usage:

import fs from 'node:fs/promises'
import { TOC } from 'react-markdown-toc/server'

async function App() {
  const markdown = await fs.readFile('.example.md', 'utf-8')
  return <TOC markdown={markdown} className='ml-4' ul='pl-4' />
}

Props

Client Component

The client component allows full customization of rendering, including the functions for rendering the list, list items, and links.

Example Usage:

Use shadcn/ui to implement a collapsible TOC list.

Preview Link

import { useRouter } from 'next/navigation'
import { fromMarkdown } from 'react-markdown-toc'
import { TOC } from 'react-markdown-toc/client'
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible'

function CustomTOC({ markdownString }) {
  const router = useRouter()
  const toc = fromMarkdown(markdownString)
  return (
    <TOC
      toc={toc}
      scrollAlign='start'
      renderList={children => (
        <CollapsibleContent className='pl-4 overflow-hidden data-[state=open]:animate-collapsible-down data-[state=closed]:animate-collapsible-up'>
          {children}
        </CollapsibleContent>
      )}
      renderListItem={(children, open) => <Collapsible open={open}>{children}</Collapsible>}
      renderLink={(children, href, active) => (
        <CollapsibleTrigger>
          <span
            data-active={active}
            role='button'
            onClick={() => {
              router.push(href, { scroll: false })
              const target = document.querySelector(href)
              target?.scrollIntoView({ behavior: 'smooth' })
            }}
          >
            {children}
          </span>
        </CollapsibleTrigger>
      )}
    />
  )
}

Props

Contribution

Contributions are always welcome!

License

MIT