Tree

A hierarchy whose branches open and close, with the WAI-ARIA tree keyboard model.

Import

ts
import { Tree } from '@k8ordo/ui';

Usage

Pass the nodes as a tree of { id, label, icon?, children? }. Up and Down move between the visible nodes, Right opens a branch and then moves to its first child, and Left closes it or moves to the parent. Home / End, Enter / Space to select, and typing a first letter work too.

  • src
    • index.ts
  • package.json
  • README.md
tsx
<Tree
  defaultExpandedIds={['src']}
  items={[
    {
      id: 'src',
      label: 'src',
      children: [
        {
          id: 'components',
          label: 'components',
          children: [{ id: 'button', label: 'button.tsx' }],
        },
        { id: 'index', label: 'index.ts' },
      ],
    },
    { id: 'readme', label: 'README.md' },
  ]}
  label="Files"
/>

Owning the Open Branches and the Selection

The open branches (expandedIds) and the selection (selectedId) can be yours. onChange receives the id of the node picked.

  • src
    • components
      • button.tsx
      • card.tsx
    • index.ts
  • package.json
  • README.md

Selected: card

tsx
const [expandedIds, setExpandedIds] = useState<readonly string[]>(['src']);
const [selectedId, setSelectedId] = useState<string | null>(null);

<Tree
  expandedIds={expandedIds}
  items={files}
  label="Files"
  onChange={setSelectedId}
  onExpandedChange={setExpandedIds}
  selectedId={selectedId}
/>

Props

items
Type: readonly TreeItem[]
Default: -
label
Type: string
Default: -
defaultExpandedIds?
Type: readonly string[]
Default: -
defaultSelectedId?
Type: string|null
Default: null
expandedIds?
Type: readonly string[]
Default: -
onChange?
Type: (id: string) => void
Default: -
onExpandedChange?
Type: (ids: readonly string[]) => void
Default: -
selectedId?
Type: string|null
Default: -

Type base (some attrs are managed internally): HTMLAttributes<HTMLUListElement>