1.0.8 • Published 4 years ago

use-page-headings-tree v1.0.8

Weekly downloads
5
License
MIT
Repository
github
Last release
4 years ago

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 = (
    pageHeadingNodes: NodeList,
    callback: (treeNodes: TreeNode[]) => void,
    defaultToExpand: bool,
    ) => { ... }

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.

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.1.2

4 years ago

0.1.1

4 years ago

0.1.0

4 years ago