Skip to content

FlatTree

FlatTree

A tree built from flat data (WAI-ARIA Tree View pattern) that can render only the items in view, for trees of thousands of items. Its model comes from useFlatTree(items, options): items listed with a parentValue, in any order, the expanded and the checked state. The tree renders the visible items (the roots and the children of every expanded branch) as sibling role="treeitem" elements with aria-level, aria-setsize and aria-posinset from the data, aria-expanded on branches, and the nested Tree's chevron, checkbox and radio.

tsx const model = useFlatTree(items, { defaultExpandedItems: ['docs'] }); const virtualWindow = useVirtualWindow({ itemSize: 28 }); <FlatTree aria-label="Files" model={model} {...model.getTreeProps()} virtualWindow={virtualWindow} style={{ height: 400 }} />

Windowing: with virtualWindow the tree is the scrolling element (it needs a bounded height), renders the items in view plus the window's overscan and spacers for the others, and every item is exactly the window's itemSize tall. The server renders the first window. Keys move over the whole visible list, scrolling an item that is not rendered into view before focusing it, and the focused item stays rendered (and focused) while it is scrolled away.

Keyboard: a single tab stop, on the focused item while focus is inside, else on the selected item while it is visible, else on the first enabled item; Tab leaves the tree. Up/Down move between the visible items, Home/End to the first and last, Right expands a collapsed branch or moves to its first child, Left collapses an expanded branch or moves to the parent (both mirrored in right-to-left layouts), Enter activates (and toggles a branch), and so does Space unless the tree has checkboxes, * expands the sibling branches, and typing moves to the next visible item whose label starts with the typed text (items under a collapsed branch are not searched). The focused item stays the focused item (rendered, and the tab stop) while focus is in a popup that its content opened, such as a menu in a portal, so the popup can return focus to it.

navigationMode="treegrid" makes it a WAI-ARIA treegrid instead: role="treegrid", each item a role="row" (with aria-level, aria-posinset, aria-setsize, aria-rowindex and aria-expanded) whose content is in gridcells, with more cells from renderCells and the treegrid keys of APG (rows, cells, Enter into a cell's controls); the nested Tree's own navigationMode="treegrid" changes the keyboard only and keeps its tree roles. Default rendering is unchanged.

Selection, as the nested Tree: selected and onItemSelect (single selection and activation, with radios in selectionMode="single"), current, and with selectionMode="multiple" a checkbox on every item bound to the model's checkedItems (Space or a click on the checkbox toggles it, and checks cascade). An item whose data is disabled is aria-disabled, is skipped by the keys and typeahead, never holds the tab stop (except while a pointer press has focused it), and is neither activated, expanded nor checked by the user (a check of its parent still includes it).

When a branch collapses around the focused item (from code), focus moves to that branch, so it never falls to the page. Items expand and collapse at once, without motion: there is no child group to animate. A selected item under a collapsed branch is not the tab stop until it is visible again.

FlatTree.Item is the row the tree renders for each visible item (it is not written by hand); it is also exported as FlatTreeItem for React Server Components, which cannot use the dotted form.

Examples

Default

Documents
README.md
export const Default: Story = {
  args: {
    defaultExpandedItems: ['docs'],
  },
};

Checkable

Documents
Work
Annual Report.docx
Presentation.pptx
README.md
export const Checkable: Story = {
  args: {
    'aria-label': 'Files to back up',
    selectionMode: 'multiple',
    defaultExpandedItems: ['docs', 'work'],
    defaultCheckedItems: ['work'],
  },
};

Treegrid

Documents
Work
Annual Report.docx
48 KB
Presentation.pptx
2.1 MB
README.md
3 KB
export const Treegrid: Story = {
  args: {
    'aria-label': 'Files',
    navigationMode: 'treegrid',
    style: { width: 420 },
    defaultExpandedItems: ['docs', 'work'],
    renderCells: (row) => [
      SIZES[row.item.value],
      <Button
        key="open"
        size="small"
        appearance="subtle"
        aria-label={`Open ${row.item.label ?? row.item.value}`}
      >
        Open
      </Button>,
    ],
    slotProps: { cell: { className: 'min-w-20 justify-end' } },
  },
  argTypes: { renderCells: { control: false } },
};

Five Thousand Nodes

Archive
Entry 1
Entry 2
Entry 3
Entry 4
Entry 5
Entry 6
Entry 7
Entry 8
Entry 9
Entry 10
Entry 11
Entry 12
Entry 13
Entry 14
Entry 15
Entry 16
Entry 17
Entry 18
Entry 19
Entry 20
Entry 21
Entry 22
Entry 23
Entry 24
Entry 25
Entry 26

Mounted items: 0 of 4,334 visible (5,000 in the tree)

export const FiveThousandNodes: Story = {
  args: {
    'aria-label': 'Archive',
    items: FIVE_THOUSAND,
    defaultExpandedItems: ['archive'],
    className: 'h-100',
  },
  render: (args) => <FiveThousandTree {...args} />,
};

Props

NameTypeRequiredDefaultDescription
modelFlatTreeModelYes

The tree's model, from useFlatTree: the visible rows, the expanded and the checked state.

virtualWindowVirtualWindowNo

Renders only the items in view (and a few beyond), from useVirtualWindow({ itemSize }). The tree is then the scrolling element: give it a bounded height (a class or a style). Every item is exactly itemSize pixels tall, so its content must fit in one row (the rows are not measured: a window that measures its rows lays the tree out from its estimate). Without it every visible item is rendered.

The tree element is then no tab stop of its own while an item is (tabIndex -1, as Firefox would stop on a scroller; a tabIndex you pass wins), and the browser's scroll anchoring is off on it (the window lays the items out): when rows are inserted or removed above the focused item while it is in view (*, or a change of the model from code), the tree moves the view with it, so it stays where it was.

renderItem(item: VisibleFlatItem & { checked?: CheckState }) => React.ReactNodeNothe item's `label`, else its `value`

The content of an item, from its row: the item data with its level, position, set size, expanded state and, in multiple mode, its check state. Called for the rendered items only.

navigationMode'tree' | 'treegrid'No'tree'

How the tree is built and moved through. 'tree' (the default) is the WAI-ARIA tree view: role="tree" with role="treeitem" items, one tab stop on an item. 'treegrid' is the WAI-ARIA treegrid: role="treegrid" (with aria-rowcount), each item a role="row" with aria-level, aria-posinset, aria-setsize, aria-rowindex and, on a branch, aria-expanded, and its content in role="gridcell" elements: the first holds the chevron, the check and what renderItem returns, and renderCells draws the others. A row has no aria-checked (its checkbox does). Fluent UI's Tree navigationMode (whose 'treegrid' keeps the tree roles; the nested Tree does the same here).

The keys of a treegrid (APG): on a row, Down and Up move to the next and previous row, Home and End (also with Ctrl) to the first and last row, Right expands a collapsed branch, else moves into the row's first cell (it no longer moves to the first child: Down does), Left collapses an expanded branch (else it does nothing: the focus stays), and Enter, Space, * and typing act on the row as in a tree. On a cell, Left and Right move between the row's cells (Left on the first returns to the row; both mirrored in right-to-left layouts), Up and Down to the cell of the same column in the previous and next row, Home and End to the first and last cell of the row, Ctrl+Home and Ctrl+End to the same column of the first and last row, and Enter or F2 moves focus to the cell's first control (a button, a link), where Escape returns to the cell and the control's own keys apply. The tree keeps one tab stop, a row or a cell; the controls in cells are taken out of the Tab order (tabindex="-1", also those that render later) and reached with Enter. A click on a cell other than the first, and on what is in it, never activates the row.

renderCells(item: VisibleFlatItem & { checked?: CheckState }) => readonly React.ReactNode[]No

The content of a row's further cells, in order, in navigationMode="treegrid": for each rendered row, the item with its level, position, set size, expanded state and check state. Each node is drawn in a role="gridcell" element after the first cell, so a value is a column (a size, a date, a button). Return the same number of cells for every row; a row with fewer keeps the last column for the keys that move between rows. Without a treegrid it is ignored (a development warning). Pure, and called for the rendered rows only.

selectionMode'none' | 'single' | 'multiple'Nothe model's mode (`model.getTreeProps().selectionMode`)

How items are selected, as the nested Tree's selectionMode. 'multiple' draws a checkbox on every item, bound to the model's checked items (create the model with selectionMode: 'multiple'); 'single' draws a radio for selected. Spread model.getTreeProps() on the tree to pass the model's mode.

selectedstring | nullNo

Value of the selected item. When set (also to null), every item carries aria-selected, and the selected item is where keyboard focus enters the tree while it is visible. It has no effect with selectionMode="multiple" (a development warning). With selectionMode="single" every item carries aria-selected even while it is not set (a development warning: the radios need it).

currentstring | nullNo

Value of the current item (for example the open page): it gets aria-current="true".

onItemSelect(value: string) => voidNo

Called with an item's value every time it is activated (a click on its row, Enter, or Space unless the tree has checkboxes), also when the same item is activated again.

refReact.Ref<HTMLDivElement>No

Ref to the role="tree" element (role="treegrid" with navigationMode="treegrid").

slotProps{ row?: SlotPart<'div'>; expandIcon?: SlotPart<'svg'>; indicator?: SlotPart<'span'>; label?: SlotPart<'span'>; cell?: SlotPart<'div'> }No

Props for the elements every item draws, by part: each FlatTree.Item is rendered by the tree, never written by hand, so the parts of all of them are given here once. The items read the object from the tree's context: an object that keeps its identity across renders (defined outside the component, or memoised) changes that context only when the tree's state changes. Each part is merged into the part's own props: your classes after the part's (yours win a conflict), your styles over its styles, your attributes and handlers added, your ref attached (to the part of every rendered item). Every attribute an item sets on a part is locked and keeps the item's value, and no part takes a role, a tab index or the markers by which the tree reads an item (its row and its checkbox), so a part changes neither the tree's items, its one tab stop nor which clicks an item takes. A part takes no children (the item draws their content: the chevron, the check marks and what renderItem returns); the treeitem elements take no props of yours. Apart from the checkbox (below), no part carries a handler of the item: an event on a part reaches the item and the tree after your handler, as one on the content does, and preventDefault() in yours skips their handling of it there too: a click you prevent on the row, the chevron, the radio or the label neither activates nor expands the item. While an item is disabled (its data's disabled), your onClick on its parts is not called, as the item activates on no click. Fluent UI's FlatTreeItem takes the parts of its TreeItemLayout as slots of their own (main for the label, expandIcon, selector for the checkbox or radio).

Any other prop is passed to the element it renders (HTMLDivElement).

Parts

  • row
  • expandIcon
  • indicator
  • label
  • cell
  • FlatTree.Item

Stable class names

PartClass
rootwave-flat-tree
spacerwave-flat-tree__spacer