Tree
Render hierarchical data with createTree, with expansion, selection, cascading checkboxes, lazy loading, and virtualization.
- src
- docs
- package.json
- LICENSE
Anatomy#
tree.Tree is the tree root. Each item is a tree.Item (treeitem) that holds a row and,
when it has children, a content wrapper around a nested group. With virtualizer, there
are no nested groups: every visible item is a flat row inside the root, which is also the scroll
container.
Usage#
Use Tree for hierarchical data that users expand, select, or check, such as files, categories, or permissions. Use List for flat data, Accordion to disclose sections of content, and Sidebar or NavigationMenu for site navigation.
Tree has no static component. Call createTree(options) inside a component, then render the
bound tree.Tree. The instance owns all state, so each call creates an independent tree.
Always name the tree with aria-label or aria-labelledby on tree.Tree.
Options and props#
Behavior is configured on createTree; presentation is configured on tree.Tree. The generated
API reference below lists tree.Tree and part props. createTree options are listed here.
| Concern | createTree options |
|---|---|
| Data | items (accessor), getKey, getChildren, getLabel, isDisabled, isLeaf |
| Expansion | expandedKeys, defaultExpandedKeys, onExpandedKeysChange, expandOnClick (true), trigger (true) |
| Selection | selectionMode ('single' by default, 'multiple', or 'none'), selectedKeys, defaultSelectedKeys, onSelectedKeysChange |
| Checking | checkable (false), checkCascade (true), checkedKeys, defaultCheckedKeys, onCheckedKeysChange |
| Lazy loads | loadChildren, onLoadChildrenComplete, onLoadChildrenError |
| Other | getIcon (default item icon), typeahead (true), onAction (↵) |
| Concern | tree.Tree props |
|---|---|
| Rendering | itemRender, actionRender, virtualizer |
| Icons | expandIcon ('icon-chevron-right'), loadingIcon ('icon-loading') |
| Presentation | size, variant, indentGuide, transition, forceMount, classes, styles |
createTree reads options reactively. Pass changing or controlled values as getters, for example
get selectedKeys() { return selected() }; a plain value is read once.
Keys are strings returned by getKey and must be unique across the whole tree. If a key repeats,
the first occurrence wins. getLabel provides the accessible name and the typeahead text; it
defaults to the item itself for strings and to the key otherwise.
Instance#
createTree returns one object with reactive state, methods, and bound parts. Read state in JSX or
effects like any signal.
| Member | Description |
|---|---|
expandedKeys, selectedKeys, checkedKeys, loadingKeys |
Current keys, read-only. |
focusedKey |
Key of the item that holds focus while focus is inside the tree. |
flattenedItems |
Visible items in display order. |
expand, collapse, toggle, expandAll, collapseAll |
Change expansion by key. Disabled branches are skipped. |
expandTo(key) |
Expands every ancestor so the item becomes visible. |
select, deselect, toggleSelect, selectAll, clearSelection |
Change selection by key. selectAll only works in 'multiple' mode. |
check, uncheck, toggleCheck |
Change the check state by key, cascading when checkCascade is on. |
focus(key) |
Expands collapsed ancestors, scrolls the item into view, and moves DOM focus to it. |
getItem(key), isLoading(key) |
Read one item handle or its loading state. |
Tree, Item, ItemTrigger, ItemCheckbox, ItemIcon, ItemLabel, ItemAction |
Components bound to this instance. |
getItem(key) returns a stable item handle (TreeT.ItemInstance<T>), and itemRender,
actionRender, getIcon, and onAction receive the same handle. Its fields are reactive, and it
carries per-item actions:
- Data:
key,raw,label,parentKey,children. - Position:
level(one-based),posInSet,setSize,isLastChild,hasChildren,isLeaf. - State:
isExpanded,isSelected,isFocused,isLoading,isDisabled,checkedState('checked','unchecked', or'indeterminate'). - Actions:
expand(),collapse(),toggle(),select(),toggleSelect(),toggleCheck(),focus().
Disabled items are skipped by keyboard navigation and cannot be focused, selected, expanded, or checked.
Expansion#
Use defaultExpandedKeys for uncontrolled expansion, or expandedKeys with onExpandedKeysChange to
own it.
Clicking a branch row toggles it, and the trigger chevron always toggles. Set expandOnClick: false
so row clicks only select. Set trigger: false to render no chevron; rows then always toggle,
whatever expandOnClick says.
Branch height animates by default; set transition={false} on tree.Tree to turn it off.
Collapsed branches unmount their children unless forceMount. Neither prop applies
with virtualizer, which has no nested groups.
Selection#
selectionMode defaults to 'single'.
'single': clicking a row selects only that row.'multiple': Ctrl or Cmd click toggles a row, ⇧ click selects a range of visible rows, and Ctrl+A selects every enabled item, including items inside collapsed branches.'none': rows cannot be selected, andaria-selectedis omitted.
Control selection with selectedKeys and onSelectedKeysChange.
Checkboxes#
Set checkable: true to give every item a check state. The default item then renders a
tree.ItemCheckbox in each row, and each treeitem exposes aria-checked.
With checkCascade on (the default), checking a branch checks its enabled descendants, and a
branch whose descendants are partly checked becomes indeterminate. Set checkCascade: false to
check each item independently.
checkedKeys and onCheckedKeysChange use the same keys, including keys of items that have not
loaded yet. A checked key under a lazy branch applies once its item loads. With checkCascade on,
children loaded under a checked branch start checked.
In a custom itemRender, place tree.ItemCheckbox yourself. It follows the tree size and the
item’s check state. It is hidden from assistive technology and removed from the tab order because
the treeitem carries aria-checked; Space on the item toggles it. Change its glyphs
with checkedIcon and indeterminateIcon.
Lazy children#
Provide loadChildren to fetch children on demand. An item becomes a lazy branch when
getChildren returns undefined for it and isLeaf does not return true. Return an empty
array from getChildren, or mark the item with isLeaf, when it can never have children.
Expanding a lazy branch waits for the promise. While it loads, the trigger shows loadingIcon,
the item sets aria-busy, and its key appears in loadingKeys. On success the branch expands and
onLoadChildrenComplete runs. On failure onLoadChildrenError runs and the branch stays
collapsed, so expanding it again retries. Lazy keys in defaultExpandedKeys or expandedKeys load
the same way.
Loaded children are cached per key while items() keeps returning the same item object for that
key. Returning a new object for a key drops its cached children and loads them again: right away
when the branch is expanded, otherwise on its next expansion.
Virtualization#
Pass a virtualizer from createListVirtualizer to render only the rows near the viewport. The
tree.Tree root becomes the scroll container, so give it a bounded height and overflow-auto.
Keyboard focus and tree.focus(key) scroll through the virtualizer, so they reach rows outside the
window.
Expanded branches are flattened into one list. Every row keeps aria-level, aria-posinset, and
aria-setsize, so assistive technology still reads the full hierarchy.
Drag to move items#
createTreeSortable from moraine/dnd (needs @dnd-kit/dom) moves items by dragging. Wrap
tree.Tree in sortable.Provider, call sortable.useNode(item) in itemRender, and spread its
props onto tree.Item. onMove reports the new parentKey and sibling index;
moveTreeNode applies it to children-shaped data.
- The top and bottom quarters of a row drop before and after it; the middle drops inside, as the
last child, when
canNestallows it. Dropping after an expanded item with children makes the source its first child, which is where the indicator line sits. - Moves into the dragged item or its descendants are rejected. Pass
canDropfor other rules. - Hovering inside a collapsed item for 600 ms expands it, which also loads lazy children. Set
expandDelayto change or disable it. - The tree styles the drag: a copy stays in place while the dragged item follows the pointer at 60%
opacity, the row under the pointer keeps its hover background,
beforeandafterdraw a straight line from the label start, andinsiderings the row. These styles followdata-dnd-dragginganddata-drop-positionontree.Item; override them through therowslot. - After the drop, the moved item slides from where it was released into its new place. A drop
inside a collapsed item expands it first. Set
dropAnimation: falseto place it at once. - Keyboard dragging starts only from
node.handleRef, so Space and ↵ on an item keep selecting and activating it. Arrow keys move along the visible rows. - With a
virtualizer, passrangeExtractor: sortable.rangeExtractortocreateListVirtualizerso the dragged row stays mounted while it is scrolled out of view. moveTreeNodeonly moves nodes that are in your data. Children fromloadChildrenlive in the tree’s cache, and a moved ancestor gets a new object, so merge loaded children into your data before moving them.
Custom items#
itemRender renders one visible item and receives its item handle. Return a tree.Item with
item={item} as the root, then compose the bound parts inside it in this order: tree.ItemTrigger,
tree.ItemCheckbox, tree.ItemIcon, tree.ItemLabel, your own content, and tree.ItemAction last.
Without itemRender, the default item renders the trigger, the checkbox when checkable, the icon
from getIcon, the label, and the actionRender actions.
tree.ItemTriggertoggles the branch and is hidden from assistive technology. Passiconto change the chevron for one item, orchildrento replace it.tree.ItemLabelshowslabel. Passchildrento render other content.tree.ItemIconrenders theiconyou pass. UsegetIconinstead when you keep the default item.
Icons#
getIcon returns the prefix icon of the default item. It receives the item handle, so the icon
can follow hasChildren, isExpanded, or isLoading. Return undefined for no icon.
On tree.Tree, expandIcon replaces the chevron of every item and loadingIcon replaces the
glyph shown while a branch loads.
Row actions#
actionRender adds trailing controls to every row of the default item, inside tree.ItemAction.
Clicks inside the actions never select or expand the item. Actions are always visible; to reveal
them on hover, style the action slot with the group/tree-row group that every row sets.
The tree keeps a single tab stop and does not manage focus inside actions. Set
tabIndex={item.isFocused ? 0 : -1} on each control so ⇥ from the focused item
reaches only that row’s actions.
Indentation and guides#
Each row indents by its depth times --mo-tree-indent. Set the geometry variables in the
tree.Tree style; every item reads them from the root.
| Variable | Default | Description |
|---|---|---|
--mo-tree-indent |
1.25rem |
Indentation added per nesting level. |
--mo-tree-gap |
Size dependent | Gap between the trigger, icon, and label. |
--mo-tree-gutter |
0.25rem |
Horizontal margin between rows and the tree edge. |
--mo-tree-pad |
0.5rem |
Row start padding before indentation. |
Indent guides are on by default. Each row renders one guide element per ancestor level inside an
aria-hidden wrapper, in nested and virtual mode alike. Guides follow right-to-left layouts and
stay visible in forced-colors mode. Restyle them with classes.guide, or set indentGuide={false}
to render none.
Keyboard interaction#
Only one item is in the tab order at a time. Arrow keys move focus between visible items and skip disabled ones. In right-to-left layouts, ← and → swap.
| Key | Action |
|---|---|
| ↓ / ↑ | Moves focus to the next or previous visible item. |
| → | Expands a collapsed branch; on an expanded branch, moves focus to its first child. |
| ← | Collapses an expanded branch; otherwise moves focus to the parent. |
| ↖ / ↘ | Moves focus to the first or last visible item. |
| ↵ | Selects the item, or toggles the branch when selectionMode is 'none'. Then calls onAction when provided. |
| Space | Toggles the check state when checkable; toggles selection in 'multiple' mode; selects the item in 'single' mode. |
| ⇧ + arrows, ↖, ↘ | Moves focus and extends the selection in 'multiple' mode. |
| Ctrl+A / Cmd+A | Selects every enabled item in 'multiple' mode. |
| * | Expands every enabled sibling of the focused item. |
| Printable characters | Moves focus to the next item whose text starts with the typed text. Turn off with typeahead: false. |
Examples#
Browse project files#
Describe nested data with getKey and getChildren, then render tree.Tree. Clicking a branch
row or its chevron toggles it.
Drive expansion from page state#
Control expandedKeys with onExpandedKeysChange, and call expandAll, collapseAll, or expandTo
from toolbar buttons.
Expand only from the chevron#
Set expandOnClick: false so clicking a row selects it and only the chevron expands or collapses
it.
Select several folders#
Set selectionMode: 'multiple' and expandOnClick: false so row clicks only change the
selection. Use Ctrl, Cmd, or ⇧ clicks to select more.
Grant permissions with cascading checkboxes#
Set checkable: true and selectionMode: 'none'. Checking a group checks everything inside it,
and partly checked groups show an indeterminate state.
Load folders on demand#
Provide loadChildren and mark files with isLeaf. Each folder loads the first time it expands
and shows a loading icon until its children arrive.
Render ten thousand rows#
Pass a virtualizer from createListVirtualizer, and give the tree a bounded
height. Expanded branches join the same virtual list.
Move files and folders by dragging#
Drag a grip, or Tab to it and press Space, then the arrow keys. Only folders accept drops inside,
and hovering over the collapsed docs folder opens it.
Add counts and custom icons#
Return a tree.Item from itemRender and compose the bound parts with your own content, such as a
Badge with a count and a tree.ItemIcon per item.
Add row actions#
Pass actionRender to add a button and a dropdown menu to each row. The action slot hides them
until the row is hovered, focused, or its menu is open. Each control sets
tabIndex={item.isFocused ? 0 : -1}, so ⇥ from an item reaches only its actions.
API Reference#
Attributes#
data-checkeddata-disableddata-expandeddata-indeterminatedata-leafdata-loadingdata-selecteddata-uncheckeddata-closeddata-transitiondata-transitioningProps#
Tree#
Renders a <ul> element by default.
Item#
Renders a <li> element by default.
ItemTrigger#
Renders a <span> element by default.
ItemCheckbox#
Renders a <button> element by default.
ItemIcon#
Renders a <span> element by default.
ItemLabel#
Renders a <span> element by default.
ItemAction#
Host props of the action container; children are the action controls. Renders a <div> element by default.