One of the most common forms of a tree is a single selection tree that only
allows one item to be selected at a time. This example will render a very simple
folder tree and show how items are linked together and rendered within the tree
along with an example of using the
useTreeItemSelection hook returns an object containing the following props
to pass to the
Tree component to get selection behavior:
selectedIds- A list of the current selected ids within the tree.
onItemSelection- A callback that updates the
selectedIdswhen an item within the tree is clicked
onMultiItemSelection- A callback that updates the
selectedIdswhen a "batch selection" occurs. This callback will never be called if the second argument for this hook is omitted or set to
multiSelect- Boolean if multi-select behavior is enabled for this tree. The default is
useTreeItemExpansion hook returns an object containing the following props
to pass to the
Treecomponent to get expansion behavior:
expandedIds- A list of the current expanded ids within the tree.
onItemExpansion- A callback that updates the
expandedIdswhen a tree item should be expanded or collapsed
onMultiItemExpansion- A callback that updates the
expandedIdswhen a "batch expansion" occurs (pressing the asterisk
To create a multi-selectable tree, all that is required is to enable the
multiSelect argument on the
useTreeItemSelection hook. Now multi tree items
will be selectable and the additional keyboard shortcuts for selecting items
will be enabled.
Now that you've learned a bit about how to use the
Tree component to render
simple trees, let's look at how we can customize how each item is rendered with
getItemProps prop on the
This prop can be used to add additional styling or general
ListItem props that
you'd like to not store in your tree and dynamically apply to each item. This
function will provide the current
item merged with the
expanded booleans representing the state of the item.
The example below will render a simple "code file tree" by dynamically applying icons based on file types and overriding some styles when focused or selected.