Hook
/ API ReferenceHook
/ API ReferenceuseTree
A hook that provides a tree of nodes and actions to manipulate it.
It uses the @weser/tree package under the hood and combines it with React's state management hooks for seamless integration.
Important note
It strips all the rootNode parameters and prepopulates the interal tree
state instead.
The Gist
'use client'
import { useTree } from '@weser/hook'
type Node =
| {
id: string
children: Array<Node> | null
type: 'root'
}
| {
id: string
children: Array<Node> | null
type: 'box'
padding: number
margin: number
}
| {
id: string
children: null
type: 'text'
size: number
color: string
}
const initialTree = {
id: 'root',
children: [],
type: 'root',
}
function Component() {
const [tree, { create, add }] = useTree<Node>(initialTree)
function addBox() {
const newBox = create({ type: 'box', padding: 10, margin: 10 })
add('root', newBox)
}
function addText() {
const newText = create({
type: 'text',
size: 16,
color: 'black',
})
add('root', newText)
}
function TreeNode({ node }: { node: Node }) {
return (
<div>
{node.type}
<button onClick={() => remove(node.id)}>Remove</button>
{node.children?.map((child) => (
<TreeNode key={child.id} node={child} />
))}
</div>
)
}
return (
<div>
{tree.children?.map((node) => <TreeNode key={node.id} node={node} />)}
<button onClick={addBox}>Add Box</button>
<button onClick={addText}>Add Text</button>
</div>
)
}
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| initialTree | T | The initial tree. |
Returns
([T, Object]) A tuple where the first element is the tree and the second element is an object containing all the methods from the @weser/tree package with the first parameter (rootNode) stripped. All the mutating methods update the internal tree state instead of returning a new tree.
© 2024-present Robin Weser. All Rights Reserved.