Tree

A collapsible hierarchy with real keyboard navigation — arrow keys move by what is visible, one tab stop for the whole tree, and ARIA that says where each row sits in its branch.

src/components/ui/tree.tsx

About

From the component's own source, where it was written.

A collapsible hierarchy with full keyboard navigation.

The generalisation of FileTree — anything nested: a JSON document, a dependency graph, a causal chain.

Two things are worth knowing. Navigation runs over a *flattened* list of the currently visible nodes, because arrow keys move by what is on screen, not by tree depth: pressing Down on the last child of a collapsed-sibling branch has to land on the next visible row, wherever that sits in the hierarchy.

And the tree owns exactly one tab stop (tabIndex roves with the active row), per the ARIA practices — a tree of two hundred nodes that puts every row in the tab order is unusable with a keyboard.

Install

npx astralyx-ui add tree

Usage

import { Tree } from '@/components/ui/tree'

<Tree
  nodes={nodes}
  defaultExpanded={['src']}
  onSelect={(id) => open(id)}
/>

Composer

Change the props and the source below follows.

  • src
  • components
  • button.tsx4.1 kB
  • tree.tsx6.8 kB
  • index.css12 kB
  • README.md2 kB
Props
tsx
<Tree
  nodes={nodes}
  defaultExpanded={['src', 'components']}
  guides={true}
/>

Examples

File hierarchy

API

Generated from the source, so it cannot fall behind the code. One table per exported component, then hooks, functions and types.

Tree

Extends Omit<ComponentProps<'ul'>, 'onSelect'>.

PropTypeDefaultDescription
nodesTreeNode[]requiredRecursive: { id, label, icon?, meta?, children?, disabled? }.
defaultExpandedstring[][]Controlled or uncontrolled expansion, by node id.
expandedstring[]—Controlled or uncontrolled expansion, by node id.
onExpandedChange(expanded: string[]) => void—Controlled or uncontrolled expansion, by node id.
selectedstring—Selection. Clicking a branch toggles it; clicking a leaf selects it.
onSelect(id: string) => void—Selection. Clicking a branch toggles it; clicking a leaf selects it.
guidesbooleantrueIndent guides.

Types

TreeNode

A collapsible hierarchy with full keyboard navigation.

FieldTypeDescription
idstring—
labelReactNode—
icon?ReactNode—
meta?ReactNodeRight-aligned annotation — a count, a size, a status.
children?TreeNode[]—
disabled?boolean—

Behaviour

TopicDetailDescription
keyboard↑ ↓ → ← Home EndUp and down move over visible rows. Right opens a branch then steps into it; Left closes it, then climbs to the parent.