use-page-headings-tree

1.0.8 • Public • Published

use-page-headings-tree

A React hook to get tree data from a list of heading nodes

NPM JavaScript Style Guide

Install

 
npm install --save use-page-headings-tree
 

Example Usage

Check out the example that uses the following code or check out the example source!

Get a list of heading nodes

useEffect(() => {
    const headingNodes = headingsContainerRef.current.querySelectorAll(
        "h2,h3,h4,h5,h6"
    );
    setPageHeadingNodes(headingNodes);
}, []);

Pass the node list, a callback to set the tree data and weather you would like the expanded attribute to be true or false by default

usePageHeadingsTree(pageHeadingNodes, setPageHeadingTree, false);

Use the tree data (recursion is the simplest method)

const renderNodeList = (node) => (
        <li key={node.id}>
            {node.text}
            {node.childNodes.length > 0 ? (
                <ul>{node.childNodes.map(renderNodeList)}</ul>
            ) : null}
        </li>
    );
);

usePageHeadingsTree hook

 
  usePageHeadingsTree = (
    pageHeadingNodesNodeList,
    callback: (treeNodes: TreeNode[]) => void,
    defaultToExpandbool,
    ) => { ... }
 

Param List

  1. pageHeadingNodes: NodeList -> NodeList as returned by Element.querySelectorAll
  2. callback: (treeNodes: TreeNode[]) => void -> callback to set an array of TreeNodes (see below)
  3. defaultToExpand: bool -> default value for TreeNode.expanded on all tree nodes.

Sample TreeNode

{
  // the id from the header element (if any)
  // useful for generating a linked table of contents
  id: "my-fancy-header-id",
 
  // the text inside the header element
  text: "some header text",
 
  // expanded attribute
  // useful for creating expand/collapse table of contents
  // default for all nodes set as third argument of usePageHeadingsTree
  expanded: true,
 
  // the total number of nested children contained in any given node
  childrenCount: 3,
 
  // root id for node
  rootId: "generated unique id",
 
  // a copy of the heading element from the original NodeList
  element: heading,
 
  // a list of child nodes
  childNodes: [],
 
  // the index of the node from the original node list
  index: 6,
}
 

License

MIT © kbrock84


This hook is created using create-react-hook.

Package Sidebar

Install

npm i use-page-headings-tree

Weekly Downloads

6

Version

1.0.8

License

MIT

Unpacked Size

1.32 MB

Total Files

22

Last publish

Collaborators

  • kbrock84