use-page-headings-tree
v1.0.8
Published
A React hook to get tree data from a list of heading nodes
Downloads
9
Maintainers
Readme
use-page-headings-tree
A React hook to get tree data from a list of heading nodes
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
pageHeadingNodes: NodeList
-> NodeList as returned byElement.querySelectorAll
callback: (treeNodes: TreeNode[]) => void
-> callback to set an array ofTreeNodes
(see below)defaultToExpand: bool
-> default value forTreeNode.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.