0.1.0 • Published 3 years ago

react-table-of-contents v0.1.0

Weekly downloads
-
License
-
Repository
-
Last release
3 years ago

Kickoff

npm install react-table-of-contents
# or
yarn add react-table-of-contents

Output:

  • A React component of table-of-contents
  • An HTML script to express the same list

React Element

import TableOfContents from "react-table-of-contents"

...

<TableOfContents headings={[
    { level: 1, id: "1-1", content: "Heading 1-1" },
    { level: 2, id: "2"  , content: "Heading 2" },
    { level: 3, id: "3-1", content: "Heading 3-1" },
    { level: 3, id: "3-2", content: "Heading 3-2" },
    { level: 1, id: "1-2", content: "Heading 1-2" },
]}>


// React component to render...
// * Heading 1-1
//     * Heading 2
//         * Heading 3-1
//         * Heading 3-2
// * Heading 1-1

HTML string

import TableOfContents from "react-table-of-contents"

const toc = TableOfContents({
        headings: [
        { level: 1, id: "1-1", content: "Heading 1" },
        { level: 2, id: "2"  , content: "Heading 2" },
        { level: 3, id: "3-1", content: "Heading 3-1" },
        { level: 3, id: "3-2", content: "Heading 3-2" },
        { level: 1, id: "1-2", content: "Heading 1" },
    ]
})

console.log(toc.toHtml())

// Note: You can decide your class names. See below for detail.

// <ul>
// 	<li class="toc-item toc-h1">
// 		<a href="#1-1">Heading 1-1</a>
// 	</li>
// 	<ul>
// 		<li class="toc-item toc-h2">
// 			<a href="#2">Heading 2</a>
// 		</li>
// 		<ul>
// 			<li class="toc-item toc-h3">
// 				<a href="#3-1">Heading 3-1</a>
// 			</li>
// 			<li class="toc-item toc-h3">
// 				<a href="#3-2">Heading 3-2</a>
// 			</li>
// 		</ul>
// 	</ul>
// 	<li class="toc-item toc-h1">
// 		<a href="#1-2">Heading 1-2</a>
// 	</li>
// </ul>

Input

  • headings : Type { id: string, level: 1|2|3|4|5|6, content: string }[]
    • id : id attribute of the target H1~H6 element to link
    • level : Hx tag's x, has to be 1 - 6
    • content: the link text
  • classnames : Type Partial<{ item: string, h1: string, ..., h6: string }>
    • item : every list element of the table of contents has this classname (default: toc-item)
    • h* : list elements with level: * will have this classname (default: toc-h*)
    • if any of the above is not specified, use default classname and corresponding CSS config