Tree
A standalone tree view on Ark UI's tree-view machine, for repo file trees and curriculum hierarchies. Same data as TreeSelect, children animate through Collapse.
Tree shows a hierarchy that stays on the page, like a repository's files or a curriculum's circles and projects. It takes the same data as TreeSelect and TreeMultiSelect, so an app can pass one shape to all three. Use those two when the tree is a way to pick a value in a form.
Ark's tree-view machine handles selection, expansion, focus, typeahead, the keyboard and lazy loading. The kit renders the rows itself. A branch's children open through Collapse (a CSS grid-rows transition) rather than Ark's JavaScript height measurement.
import { Tree } from '@42-central/ui-react/tree';
<Tree
data={[
{
value: 'srcs',
label: 'srcs',
children: [
{ value: 'srcs/main.c', label: 'main.c' },
{ value: 'srcs/parser.c', label: 'parser.c' },
],
},
{ value: 'Makefile', label: 'Makefile' },
]}
defaultExpanded={['srcs']}
onNodeClick={(node) => openFile(node.value)}
/>Playground
Tree
Dir
Presets
Props
Code
<Tree
size="md"
multiple={false}
withCheckbox={false}
withLines
expandOnClick
disabled={false}
/>Data
data is a tree of { value, label, disabled?, children?, payload?, testId? }, the shape TreeSelect uses. A node with children is a branch, and one without is a leaf. Every value must be unique across the whole tree, so for files use the path. Tree reads two more optional fields that the pickers ignore:
hasChildren: the node is a branch whose children aren't loaded yet. See Lazy loading.icon: the node's own icon, in place of the default folder or file. Usenullfor no icon.
With a const array (or as const), selected, expanded and checked are typed as the tree's own values.
Selection
A click, or Enter, selects the row. By default only one row is selected at a time. With multiple, ⌘/Ctrl-click adds or removes a row, Shift-click and Shift+arrows extend the range, and ⌘A selects every row.
onNodeClick(node, event) fires on every click on an enabled row, whether or not the selection changes. Use it to open a file or navigate. It doesn't fire for clicks on the chevron, the checkbox or the row actions.
Expanding
By default a click on a branch row expands or collapses it. With expandOnClick={false}, only the chevron and the keyboard do. Then a click on the row only selects it, as in an editor's file explorer. Children open and close through Collapse. A closed group is inert, so its rows are out of the tab order and the accessibility tree while hidden. The animation follows prefers-reduced-motion.
Controlled
selected, expanded and checked each have a default* uncontrolled form and an on*Change callback.
Selected: nothing
Code
const [expanded, setExpanded] = useState<string[]>(['srcs']);
const [selected, setSelected] = useState<string[]>([]);
<Tree
data={FILES}
expanded={expanded}
onExpandedChange={setExpanded}
selected={selected}
onSelectedChange={setSelected}
/>Checkboxes
withCheckbox adds a checkbox to every row. It cascades like TreeMultiSelect's, using the same code. checked holds leaf values only. A branch is checked when all its enabled leaves are, and shows as mixed when only some are. Checking a branch checks its enabled leaves, and disabled leaves keep their state. Checking is separate from selection: a click on the box doesn't select the row. With the keyboard, Space checks the focused row and Enter selects it.
Lazy loading
Mark a node hasChildren and pass loadChildren(node, { signal }). The first time the branch expands, Tree calls it. The chevron turns into a spinner until the promise resolves, then the branch opens with what it returned. The loaded children stay loaded after the branch closes. If the promise rejects, the branch stays closed and onLoadError(node, error) fires. Expanding it again retries. signal aborts when the same branch is expanded again before the first call has finished.
A branch that was checked before it loaded counts as checked by itself. After its children load, they take its place in checked.
Code
<Tree
data={[
{ value: 'packages', label: 'packages', hasChildren: true },
{ value: 'package.json', label: 'package.json' },
]}
loadChildren={async (node, { signal }) => {
const res = await fetch(`/api/ls?path=${node.value}`, { signal });
return res.json();
}}
onLoadError={(node, error) => toast(`Couldn't list ${node.label}`)}
/>Icons
By default a branch shows a folder (open while expanded) and a leaf shows a file. You can change them in two ways:
- A node's own
iconwins over the defaults. Useicon: nullfor no icon on that node. iconsreplaces the kit's defaults for the whole tree, per instance. Its slots arechevron,folder,folderOpen,file,check,indeterminateandloading. Setfolder,folderOpenorfiletonullfor no icon.
Your icons are drawn as you pass them. Add className={iconStroke} (from @42-central/ui-react) for the kit's 1.5px line. The default chevron points down and turns a quarter towards the inline end while closed, so it already follows dir.
Code
<Tree.Root data={CURRICULUM} defaultExpanded={['circle-1']}>
<Tree.Label>Curriculum</Tree.Label>
<Tree.List>
{(node, state) => (
<>
<Tree.Indicator />
<Tree.Icon />
<Tree.Text />
{state.leaf && <Badge size="xs" variant="light">{node.payload.xp} XP</Badge>}
</>
)}
</Tree.List>
</Tree.Root>Indentation guides
Each level indents by 16px. The guides are the lines TreeSelect draws: a vertical line per ancestor that has more siblings below, and an elbow into each row. withLines={false} keeps the indent and drops the lines.
Row actions
actions(node, state) puts buttons at the end of each row. They show while the row is hovered or has focus. Hidden actions use visibility: hidden, which also takes them out of the tab order. Tab from the focused row reaches only that row's actions, then leaves the tree. Clicks and keys inside the actions never select the row or move the focus.
Hover a row, or focus one and press Tab.
Code
<Tree
data={FILES}
actions={(node) => (
<>
<ActionIcon size="xs" variant="subtle" aria-label={`Rename ${node.label}`} onClick={() => rename(node)}>
<Pencil className={iconStroke} />
</ActionIcon>
<ActionIcon size="xs" variant="subtle" aria-label={`Delete ${node.label}`} onClick={() => remove(node)}>
<Trash2 className={iconStroke} />
</ActionIcon>
</>
)}
/>Give each action an aria-label that names its node. A screen reader user reaches the actions from the row, so "Delete" alone wouldn't say which file.
Disabled
A node with disabled: true can't be selected, expanded, checked or clicked. Its whole subtree is disabled too. Keyboard navigation still passes over it, as the WAI-ARIA tree pattern asks. disabled on Tree disables every node. In the examples above, obj is disabled.
Right to left
The rails, chevron and actions use logical sides, so they mirror under rtl. Ark mirrors ← and → too, so ← expands. Ark reads the direction from the locale, so wrap the app in IntlProvider with an RTL locale. dir="rtl" on the page alone isn't enough.
Code
<IntlProvider locale="ar">
<Tree data={FILES} withCheckbox />
</IntlProvider>Anatomy
The data form <Tree /> is Tree.Root with a Tree.List inside. Use the parts to build your own rows.
Tree.Root: owns the state (Ark's machine, loaded children, checkboxes) and renders the root<div>. It takes every prop the data form takes exceptrenderItemandactions.Tree.Label: an optional visible name. When it's there, the tree is labelled by it. Otherwisetranslations.treeLabel(default"Tree") names it.Tree.List: therole="tree"element. It renders every node. Itschildrenis the row renderer,(node, state) => ReactNode. The tree keeps the row itself (itstreeitemrole, rails, roving focus, click and keys) and the renderer fills what comes after the rails. Leavechildrenout for the default row.Tree.Indicator: a branch's chevron, or a spinner while it loads. On a leaf it renders an empty column so labels line up. Clicking it toggles the branch without selecting it.Tree.Checkbox: the row's checkbox. It's decorative: the state is on thetreeitem'saria-checked.Tree.Icon: the node'sicon, else a folder or a file. It renders nothing when that resolves tonull.childrenreplace it.Tree.Text: the label, truncated to the row.childrenreplace it.Tree.Actions: buttons at the row's end, shown on hover or focus.
state holds { depth, leaf, selected, expanded, loading, checked, indeterminate, disabled, focused }. useTree() returns the tree's live API (Ark's expand, collapse, select, focus…) and useTreeNode() returns the row being rendered, for a part of your own.
Every row's data-testid is the node's testId, which defaults to `item-${value}`. A branch's children group is `${testId}-group`. The parts default to the row's id plus their name: -indicator, -checkbox, -icon, -text, -actions. Each part also takes its own testId. Tree.Root and Tree.List take one too. See Testing.
'use client';
import { Tree } from '@42-central/ui-react/tree';
<Tree.Root data={FILES} withCheckbox testId="files">
<Tree.Label>Files</Tree.Label>
<Tree.List>
{(node, state) => (
<>
<Tree.Indicator />
<Tree.Checkbox />
<Tree.Icon />
<Tree.Text>{state.leaf ? node.label : `${node.label}/`}</Tree.Text>
<Tree.Actions>
<DeleteButton node={node} />
</Tree.Actions>
</>
)}
</Tree.List>
</Tree.Root>Tree.Root, Tree.Label, Tree.Text and Tree.Actions accept asChild. Tree.List, Tree.Indicator, Tree.Checkbox and Tree.Icon render their own structure, so they don't.
API
Prop
Type
Accessibility
- It follows the WAI-ARIA tree view pattern through Ark's machine. The list is
role="tree"(aria-multiselectablewithmultiple), each node is atreeitemwitharia-level,aria-setsize,aria-posinsetandaria-selected, a branch hasaria-expanded, and its children sit in arole="group". - The tree is a single tab stop.
↓/↑move between visible rows.→opens a branch, then moves into it.←closes a branch, or moves to the parent.Home/Endjump to the first and last rows.*expands every sibling. Typing a few letters focuses the next matching row. Enterselects (and toggles a branch whileexpandOnClickis on).Spacedoes the same, or checks the row whenwithCheckboxis on. A checked row hasaria-checked("mixed"for a partly checked branch).- A loading branch has
aria-busy="true". A disabled node hasaria-disabled: it's skipped by selection but still reachable, so its label is read. - A closed group is
inert. Its rows are out of the tab order and the accessibility tree, as they would be withhidden, but the close animation still plays. - Row actions are reachable with Tab from the focused row. Name each one after its node.
- Under an RTL locale the rails and chevron mirror, and
←/→swap.
Changelog
Accordion
A stack of expandable sections on Ark UI's Accordion machine. Content animates via the kit's own zero-JS Collapse primitive, not Ark's JS-measured height.
Skeleton
Loading placeholder — a fixed rectangular/circular shape, or a wrap mode that sizes itself to real children and reveals them once loaded.