Tree
A hierarchy of nodes that open, close and can be chosen, with search, lazy branches and virtual scrolling.
- Beverages148
- Coffee62
- Tea54
- Soft drinks32
- Pantry231
- Household76
import { Tree, TreeNode } from '@slotted/react/tree';export default function TreeBasic() { return ( <Tree aria-label="Product categories" defaultExpandedKeys={['beverages']} defaultValue="coffee"> <TreeNode value="beverages" label="Beverages" meta="148"> <TreeNode value="coffee" label="Coffee" meta="62" /> <TreeNode value="tea" label="Tea" meta="54" /> <TreeNode value="soft-drinks" label="Soft drinks" meta="32" /> </TreeNode> <TreeNode value="pantry" label="Pantry" meta="231"> <TreeNode value="oils" label="Oils and vinegars" meta="87" /> <TreeNode value="spices" label="Spices" meta="144" /> </TreeNode> <TreeNode value="household" label="Household" meta="76" /> </Tree> );}Installation
The packages are a 0.x beta on npm, and their public API changes between beta releases without deprecation. One line installs the binding and the default theme.
pnpm add @slotted/react @slotted/theme @slotted/themesimport { Tree, TreeDefaultsProvider, TreeDescription, TreeEmpty, TreeGroup, TreeIcon, TreeLabel, TreeMeta, TreeNode } from '@slotted/react';Nodes from data
nodes renders a hierarchy you already hold, and getKey, getLabel and getChildren read it. A node written by hand suits a short, fixed tree; nodes is what expandAll, the cascade, the search and virtual scrolling need, because the children of a closed branch are not in the DOM. The buttons call the handle that handleRef gives in React and the slTree template reference gives in Angular.
- Beverages
- Pantry
- Household
import { useRef } from 'react';import { Button } from '@slotted/react/button';import { Inline } from '@slotted/react/inline';import { Stack } from '@slotted/react/stack';import { Tree, type TreeHandle } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeNodes() { const tree = useRef<TreeHandle>(null); return ( <Stack gap={3}> <Inline gap={2}> <Button size="sm" variant="outline" onClick={() => tree.current?.expandAll()}> Expand all </Button> <Button size="sm" variant="outline" onClick={() => tree.current?.collapseAll()}> Collapse all </Button> </Inline> <Tree aria-label="Product categories" handleRef={tree} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> </Stack> );}Flat rows
A backend often returns a hierarchy as rows in reading order, each with its depth. getLevel reads that depth, and no nested structure has to be built first.
- Assets1000
- Cash and equivalents1100
- Operating account1110
- Payroll account1120
- Receivables1200
- Liabilities2000
import { Tree } from '@slotted/react/tree';interface AccountRow { code: string; name: string; level: number;}const CHART: AccountRow[] = [ { code: '1000', name: 'Assets', level: 0 }, { code: '1100', name: 'Cash and equivalents', level: 1 }, { code: '1110', name: 'Operating account', level: 2 }, { code: '1120', name: 'Payroll account', level: 2 }, { code: '1200', name: 'Receivables', level: 1 }, { code: '2000', name: 'Liabilities', level: 0 }, { code: '2100', name: 'Payables', level: 1 },];export default function TreeFlatRows() { return ( <Tree aria-label="Chart of accounts" defaultExpandedKeys={['1000', '1100']} nodes={CHART} getKey={(row) => row.code} getLabel={(row) => row.name} getLevel={(row) => row.level} renderCells={(row) => ({ meta: row.code })} /> );}What opens a branch
expandOn decides what a press does. row, the default, opens a branch from anywhere on its row and also chooses it. expander leaves opening to the chevron, whose target grows to the minimum pointer size, so a press on the row only chooses. Use expander when a branch is itself something to choose.
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
import { Grid } from '@slotted/react/grid';import { Stack } from '@slotted/react/stack';import { Tree } from '@slotted/react/tree';import { Text } from '@slotted/react/typography';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeExpansion() { return ( <Grid columns={2} gap={6} minItemWidth="xs"> <Stack gap={2}> <Text size="sm" tone="muted"> The whole row </Text> <Tree aria-label="Categories, opened by the row" defaultExpandedKeys={['beverages']} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> </Stack> <Stack gap={2}> <Text size="sm" tone="muted"> The chevron alone </Text> <Tree aria-label="Categories, opened by the chevron" expandOn="expander" defaultExpandedKeys={['beverages']} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> </Stack> </Grid> );}Controlled
The selection, the open branches and the position of the keyboard are three separate values. React takes value, expandedKeys and activeKey with a change handler each; Angular binds each two ways. The request sent with a change carries its reason and cancel().
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
import { useState } from 'react';import { Stack } from '@slotted/react/stack';import { Tree, type TreeValue } from '@slotted/react/tree';import { Text } from '@slotted/react/typography';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeControlled() { const [value, setValue] = useState<TreeValue>('tea'); const [open, setOpen] = useState<readonly string[]>(['beverages']); return ( <Stack gap={3}> <Tree aria-label="Product categories" expandedKeys={open} onExpandedKeysChange={(keys) => setOpen(keys)} onValueChange={(next) => setValue(next)} value={value} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <Text size="sm" tone="muted"> Chosen: {value ?? 'none'}. Open: {open.join(', ') || 'none'}. </Text> </Stack> );}Choosing several nodes
selectionMode="multiple" draws a checkbox on every row and holds a set of keys. A press changes one node and leaves the others. Shift with an arrow key extends the selection, and Control+A chooses every visible node.
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Oils and vinegars
- Spices
- Household
import { Tree } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeMultiple() { return ( <Tree aria-label="Categories on promotion" selectionMode="multiple" defaultExpandedKeys={['beverages', 'pantry']} defaultValue={['coffee', 'oils']} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> );}Cascade
selectionCascade="descendants" makes a branch stand for what is under it. Choosing Orders chooses its three permissions, and a branch that holds part of its children draws a dash. Approve payouts is disabled, so choosing Finance leaves it as it was.
- Orders
- View orders
- Edit orders
- Issue refunds
- Finance
- View invoices
- Approve payouts
- Reports
import { Tree } from '@slotted/react/tree';interface Scope { id: string; name: string; locked?: boolean; children?: Scope[];}const SCOPES: Scope[] = [ { id: 'orders', name: 'Orders', children: [ { id: 'orders.view', name: 'View orders' }, { id: 'orders.edit', name: 'Edit orders' }, { id: 'orders.refund', name: 'Issue refunds' }, ], }, { id: 'finance', name: 'Finance', children: [ { id: 'finance.invoices', name: 'View invoices' }, { id: 'finance.payouts', name: 'Approve payouts', locked: true }, ], }, { id: 'reports', name: 'Reports' },];export default function TreeCascade() { return ( <Tree aria-label="Role permissions" selectionCascade="descendants" selectionMode="multiple" expandOn="expander" defaultExpandedKeys={['orders', 'finance']} defaultValue={['orders.view']} isNodeDisabled={(scope) => scope.locked === true} nodes={SCOPES} getKey={(scope) => scope.id} getLabel={(scope) => scope.name} getChildren={(scope) => scope.children} /> );}Selection as in a file list
selectionBehavior="replace" makes a plain press choose one row and drop the rest. Control or Command adds a row, and Shift chooses a range. Set selectionIndicator="highlight" with it, because a checkbox says that each press is independent.
- Contracts
- Contoso Foods 2026.pdf
- Fabrikam Supply 2026.pdf
- Atlas Freight renewal.pdf
- Forecasts
- Q3 demand.xlsx
- Q4 demand.xlsx
import { Tree } from '@slotted/react/tree';interface Entry { id: string; name: string; children?: Entry[];}const FOLDERS: Entry[] = [ { id: 'contracts', name: 'Contracts', children: [ { id: 'contoso', name: 'Contoso Foods 2026.pdf' }, { id: 'fabrikam', name: 'Fabrikam Supply 2026.pdf' }, { id: 'atlas', name: 'Atlas Freight renewal.pdf' }, ], }, { id: 'forecasts', name: 'Forecasts', children: [ { id: 'q3', name: 'Q3 demand.xlsx' }, { id: 'q4', name: 'Q4 demand.xlsx' }, ], },];export default function TreeReplace() { return ( <Tree aria-label="Documents" expandOn="expander" selectionBehavior="replace" selectionIndicator="highlight" selectionMode="multiple" defaultExpandedKeys={['contracts', 'forecasts']} defaultValue={['contoso', 'fabrikam']} nodes={FOLDERS} getKey={(entry) => entry.id} getLabel={(entry) => entry.name} getChildren={(entry) => entry.children} /> );}Selection indicator
selectionIndicator decides how a choice is drawn and which attribute states it: highlight writes aria-selected and checkbox writes aria-checked. The default, auto, draws a highlight for a single choice and checkboxes for several. Here a single choice draws the checkbox.
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
import { Tree } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeIndicator() { return ( <Tree aria-label="Default category" selectionIndicator="checkbox" defaultExpandedKeys={['beverages']} defaultValue="tea" nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> );}Navigation
selectionMode="none" writes no selection attribute, for a tree that opens pages. onNodeActivate in React and nodeActivate in Angular fire when a row is pressed and when Enter is pressed on it. The active node stays drawn on the page being shown.
import { useState } from 'react';import { Stack } from '@slotted/react/stack';import { Tree } from '@slotted/react/tree';import { Text } from '@slotted/react/typography';interface Page { id: string; name: string; children?: Page[];}const PAGES: Page[] = [ { id: 'inventory', name: 'Inventory', children: [ { id: 'stock', name: 'Stock levels' }, { id: 'transfers', name: 'Transfers' }, { id: 'counts', name: 'Cycle counts' }, ], }, { id: 'purchasing', name: 'Purchasing', children: [ { id: 'orders', name: 'Purchase orders' }, { id: 'suppliers', name: 'Suppliers' }, ], },];const NAMES = new Map( PAGES.flatMap((page) => [page, ...(page.children ?? [])]).map((page) => [page.id, page.name]),);export default function TreeNavigation() { const [page, setPage] = useState('stock'); return ( <Stack gap={3}> <Tree aria-label="Help center" expandOn="expander" selectionMode="none" defaultActiveKey="stock" defaultExpandedKeys={['inventory']} onNodeActivate={setPage} nodes={PAGES} getKey={(entry) => entry.id} getLabel={(entry) => entry.name} getChildren={(entry) => entry.children} /> <Text role="status" size="sm" tone="muted"> Open page: {NAMES.get(page)} </Text> </Stack> );}Row content
A row holds an icon, the name, a muted description, trailing meta and trailing controls. React takes them as props of TreeNode; Angular projects elements marked slTreeIcon, slTreeDescription, slTreeMeta and slTreeActions. One icon anywhere reserves the cell on every row, so the names stay in one column. A long name truncates before its meta.
- Contracts2
- Contoso Foods 2026.pdfSigned1.2 MB
- Fabrikam Supply master services agreement, amended.pdfDraft840 kB
- Forecasts1
- Q4 demand.xlsxEdited today96 kB
import { Glyph, Icon } from '@slotted/react/icon';import { Tree, TreeNode } from '@slotted/react/tree';export default function TreeRowContent() { return ( <Tree aria-label="Documents" defaultExpandedKeys={['contracts', 'forecasts']}> <TreeNode value="contracts" label="Contracts" meta="2"> <TreeNode value="contoso" label="Contoso Foods 2026.pdf" description="Signed" meta="1.2 MB" icon={ <Icon> <Glyph name="file-text" /> </Icon> } /> <TreeNode value="fabrikam" label="Fabrikam Supply master services agreement, amended.pdf" description="Draft" meta="840 kB" icon={ <Icon> <Glyph name="file-text" /> </Icon> } /> </TreeNode> <TreeNode value="forecasts" label="Forecasts" meta="1"> <TreeNode value="q4" label="Q4 demand.xlsx" description="Edited today" meta="96 kB" icon={ <Icon> <Glyph name="file-spreadsheet" /> </Icon> } /> </TreeNode> </Tree> );}Row content from data
With nodes, renderCells in React returns the cells of one row. In Angular, an ng-template marked slTreeCell fills one cell of every row and holds the directive of that cell. A cell left out is not drawn, and the name stays the one getLabel returns.
- Columbus, OH2 zones
- Zone A1,840
- Zone BCounting920
- Reno, NV2 zones
import { Tree } from '@slotted/react/tree';interface Location { id: string; name: string; units?: number; status?: string; children?: Location[];}const LOCATIONS: Location[] = [ { id: 'cmh', name: 'Columbus, OH', children: [ { id: 'cmh-a', name: 'Zone A', units: 1840 }, { id: 'cmh-b', name: 'Zone B', units: 920, status: 'Counting' }, ], }, { id: 'rno', name: 'Reno, NV', children: [ { id: 'rno-a', name: 'Zone A', units: 2310 }, { id: 'rno-cold', name: 'Cold storage', units: 415 }, ], },];export default function TreeCells() { return ( <Tree aria-label="Stock locations" defaultExpandedKeys={['cmh']} renderCells={(location) => ({ description: location.status, meta: location.units?.toLocaleString('en-US') ?? `${location.children?.length ?? 0} zones`, })} nodes={LOCATIONS} getKey={(location) => location.id} getLabel={(location) => location.name} getChildren={(location) => location.children} /> );}Icons by state
An icon can follow the branch it stands on. This tree controls expandedKeys and draws an open folder on every key in it.
- Contracts
- Contoso Foods 2026.pdf
- Fabrikam Supply 2026.pdf
- Atlas Freight renewal.pdf
- Forecasts
import { useState } from 'react';import { Glyph, Icon } from '@slotted/react/icon';import { Tree } from '@slotted/react/tree';interface Entry { id: string; name: string; children?: Entry[];}const FOLDERS: Entry[] = [ { id: 'contracts', name: 'Contracts', children: [ { id: 'contoso', name: 'Contoso Foods 2026.pdf' }, { id: 'fabrikam', name: 'Fabrikam Supply 2026.pdf' }, { id: 'atlas', name: 'Atlas Freight renewal.pdf' }, ], }, { id: 'forecasts', name: 'Forecasts', children: [ { id: 'q3', name: 'Q3 demand.xlsx' }, { id: 'q4', name: 'Q4 demand.xlsx' }, ], },];const FOLDER = 'M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z';const FOLDER_OPEN = 'm6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2';function FolderIcon({ open }: { open: boolean }) { return ( <Icon> <svg fill="none" stroke="currentColor" strokeLinejoin="round" strokeWidth="2" viewBox="0 0 24 24" > <path d={open ? FOLDER_OPEN : FOLDER} /> </svg> </Icon> );}export default function TreeIconByState() { const [open, setOpen] = useState<readonly string[]>(['contracts']); return ( <Tree aria-label="Documents" expandedKeys={open} onExpandedKeysChange={(keys) => setOpen(keys)} renderCells={(entry) => ({ icon: entry.children ? ( <FolderIcon open={open.includes(entry.id)} /> ) : ( <Icon> <Glyph name="file-text" /> </Icon> ), })} nodes={FOLDERS} getKey={(entry) => entry.id} getLabel={(entry) => entry.name} getChildren={(entry) => entry.children} /> );}Trailing controls
The controls in actions are always in the DOM, and each is a tab stop of its own. A press on one neither chooses nor opens the row, and the keys pressed on it are its own.
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
import { useState } from 'react';import { IconButton } from '@slotted/react/button';import { Glyph } from '@slotted/react/icon';import { Menu, MenuContent, MenuItem, MenuTrigger } from '@slotted/react/menu';import { Stack } from '@slotted/react/stack';import { Tree } from '@slotted/react/tree';import { Text } from '@slotted/react/typography';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeActionsExample() { const [last, setLast] = useState('No action yet.'); return ( <Stack gap={3}> <Tree aria-label="Product categories" defaultExpandedKeys={['beverages']} renderCells={(category) => ({ actions: ( <Menu align="end"> <MenuTrigger render={(props) => ( <IconButton {...props} aria-label={`Actions for ${category.name}`} size="sm" variant="ghost" > <Glyph name="ellipsis" /> </IconButton> )} /> <MenuContent> <MenuItem onSelect={() => setLast(`Rename ${category.name}.`)}>Rename…</MenuItem> <MenuItem onSelect={() => setLast(`Add a category under ${category.name}.`)}> Add a category </MenuItem> </MenuContent> </Menu> ), })} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <Text role="status" size="sm" tone="muted"> {last} </Text> </Stack> );}Sizes
size moves the row height, the type size, the glyph and the indent together: sm, md, the default, or lg.
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
import { Grid } from '@slotted/react/grid';import { Tree } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeSizes() { return ( <Grid columns={3} gap={6} minItemWidth="xs"> <Tree aria-label="Categories, small" size="sm" defaultExpandedKeys={['beverages']} defaultValue="coffee" nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <Tree aria-label="Categories, medium" size="md" defaultExpandedKeys={['beverages']} defaultValue="coffee" nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <Tree aria-label="Categories, large" size="lg" defaultExpandedKeys={['beverages']} defaultValue="coffee" nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> </Grid> );}Variants
plain, the default, draws no box, for a panel or a drawer that already has an edge. framed draws an edge, a radius and a shadow, for a tree that stands alone on a page.
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
import { Grid } from '@slotted/react/grid';import { Tree } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeVariants() { return ( <Grid columns={2} gap={6} minItemWidth="xs"> <Tree aria-label="Categories, plain" variant="plain" defaultExpandedKeys={['beverages']} defaultValue="coffee" nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <Tree aria-label="Categories, framed" variant="framed" defaultExpandedKeys={['beverages']} defaultValue="coffee" nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> </Grid> );}Guides
Each guide runs under the chevron of an ancestor and says which branch a row belongs to. Set guides to false for a tree of two levels, where the indent is enough.
- Beverages
- Pantry
- Oils and vinegars
- Spices
- Ground spices
- Whole spices
- Household
- Beverages
- Pantry
- Oils and vinegars
- Spices
- Ground spices
- Whole spices
- Household
import { Grid } from '@slotted/react/grid';import { Tree } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeGuides() { return ( <Grid columns={2} gap={6} minItemWidth="xs"> <Tree aria-label="Categories with guides" defaultExpandedKeys={['pantry', 'spices']} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <Tree aria-label="Categories without guides" guides={false} defaultExpandedKeys={['pantry', 'spices']} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> </Grid> );}States
A disabled node keeps its place, and the arrow keys pass over it unless navigateDisabled is set. readOnly fixes the selection while branches still open, disabled stops the whole tree, and invalid draws the edge of a framed tree in the danger tone.
- Orders
- Finance
- View invoices
- Approve payouts
- Reports
- Orders
- Finance
- View invoices
- Approve payouts
- Reports
- Orders
- Finance
- View invoices
- Approve payouts
- Reports
- Orders
- Finance
- View invoices
- Approve payouts
- Reports
import { Grid } from '@slotted/react/grid';import { Stack } from '@slotted/react/stack';import { Tree } from '@slotted/react/tree';import { Text } from '@slotted/react/typography';interface Scope { id: string; name: string; locked?: boolean; children?: Scope[];}const SCOPES: Scope[] = [ { id: 'orders', name: 'Orders', children: [ { id: 'orders.view', name: 'View orders' }, { id: 'orders.edit', name: 'Edit orders' }, { id: 'orders.refund', name: 'Issue refunds' }, ], }, { id: 'finance', name: 'Finance', children: [ { id: 'finance.invoices', name: 'View invoices' }, { id: 'finance.payouts', name: 'Approve payouts', locked: true }, ], }, { id: 'reports', name: 'Reports' },];export default function TreeStates() { return ( <Grid columns={2} gap={6} minItemWidth="xs"> <Stack gap={2}> <Text size="sm" tone="muted"> One node disabled </Text> <Tree aria-label="Permissions, one node disabled" isNodeDisabled={(scope) => scope.locked === true} selectionMode="multiple" defaultExpandedKeys={['finance']} defaultValue={['finance.invoices']} nodes={SCOPES} getKey={(scope) => scope.id} getLabel={(scope) => scope.name} getChildren={(scope) => scope.children} /> </Stack> <Stack gap={2}> <Text size="sm" tone="muted"> Read only </Text> <Tree aria-label="Permissions, read only" readOnly selectionMode="multiple" defaultExpandedKeys={['finance']} defaultValue={['finance.invoices']} nodes={SCOPES} getKey={(scope) => scope.id} getLabel={(scope) => scope.name} getChildren={(scope) => scope.children} /> </Stack> <Stack gap={2}> <Text size="sm" tone="muted"> Disabled </Text> <Tree aria-label="Permissions, disabled" disabled selectionMode="multiple" defaultExpandedKeys={['finance']} defaultValue={['finance.invoices']} nodes={SCOPES} getKey={(scope) => scope.id} getLabel={(scope) => scope.name} getChildren={(scope) => scope.children} /> </Stack> <Stack gap={2}> <Text size="sm" tone="muted"> Invalid </Text> <Tree aria-label="Permissions, invalid" invalid variant="framed" selectionMode="multiple" defaultExpandedKeys={['finance']} defaultValue={['finance.invoices']} nodes={SCOPES} getKey={(scope) => scope.id} getLabel={(scope) => scope.name} getChildren={(scope) => scope.children} /> </Stack> </Grid> );}Lazy branches
hasChildren draws a chevron on a branch whose children have not been fetched. Start the request when the branch opens and return true from isNodeLoading until it ends: a spinner takes the place of the chevron, the branch has aria-busy, and a live region announces how many items arrived. getChildrenCount states the size of the set while part of it is missing. Open an account to fetch its orders.
- Contoso Foods
- Fabrikam Supply
- Atlas Freight
import { useState } from 'react';import { Tree } from '@slotted/react/tree';interface Account { id: string; name: string; orders?: number; children?: Account[];}const ACCOUNTS: Account[] = [ { id: 'contoso', name: 'Contoso Foods', orders: 3 }, { id: 'fabrikam', name: 'Fabrikam Supply', orders: 2 }, { id: 'atlas', name: 'Atlas Freight' },];const ORDERS: Record<string, Account[]> = { contoso: [ { id: 'SO-10482', name: 'SO-10482' }, { id: 'SO-10496', name: 'SO-10496' }, { id: 'SO-10511', name: 'SO-10511' }, ], fabrikam: [ { id: 'SO-10484', name: 'SO-10484' }, { id: 'SO-10502', name: 'SO-10502' }, ],};export default function TreeLazy() { const [accounts, setAccounts] = useState(ACCOUNTS); const [open, setOpen] = useState<readonly string[]>([]); const [pending, setPending] = useState<readonly string[]>([]); function handleOpen(keys: readonly string[]) { setOpen(keys); for (const key of keys.filter((candidate) => !open.includes(candidate))) fetchOrders(key); } function fetchOrders(key: string) { const account = accounts.find((candidate) => candidate.id === key); if (account === undefined || account.children !== undefined || pending.includes(key)) return; setPending((current) => [...current, key]); setTimeout(() => { setAccounts((current) => current.map((entry) => entry.id === key ? { ...entry, children: ORDERS[key] ?? [] } : entry, ), ); setPending((current) => current.filter((candidate) => candidate !== key)); }, 1200); } return ( <Tree aria-label="Orders by account" expandedKeys={open} onExpandedKeysChange={(keys) => handleOpen(keys)} getChildrenCount={(account) => account.orders} hasChildren={(account) => account.orders !== undefined} isNodeLoading={(account) => pending.includes(account.id)} nodes={accounts} getKey={(account) => account.id} getLabel={(account) => account.name} getChildren={(account) => account.children} /> );}Loading
loading writes aria-busy on the tree while its first nodes arrive. Rows with a Skeleton as the label hold the place of the names, at widths that vary by row, and SkeletonRegion waits 200 milliseconds before it draws. Refresh locations starts a 1.5-second load.
import { useEffect, useState } from 'react';import { Button } from '@slotted/react/button';import { Skeleton, SkeletonRegion } from '@slotted/react/skeleton';import { Stack } from '@slotted/react/stack';import { Tree, TreeNode } from '@slotted/react/tree';const ROWS = [ { id: 'cmh', name: 'Columbus, OH' }, { id: 'rno', name: 'Reno, NV' }, { id: 'sav', name: 'Savannah, GA' }, { id: 'dfw', name: 'Dallas, TX' },];export default function TreeLoading() { const [loading, setLoading] = useState(true); useEffect(() => { if (!loading) return; const timer = setTimeout(() => setLoading(false), 1500); return () => clearTimeout(timer); }, [loading]); return ( <Stack align="start" gap={3}> <Button size="sm" variant="outline" onClick={() => setLoading(true)}> Refresh locations </Button> <SkeletonRegion delay={200} loading={loading} messages={{ label: 'Loading locations' }} minDuration={400} > <Tree aria-label="Stock locations" loading={loading}> {ROWS.map((row) => ( <TreeNode hasChildren key={row.id} label={loading ? <Skeleton /> : row.name} textValue={row.name} value={row.id} /> ))} </Tree> </SkeletonRegion> </Stack> );}Empty
emptyContent in React and an element marked slTreeEmpty in Angular show when the tree holds no node. The tree keeps its role and its name.
import { Tree } from '@slotted/react/tree';export default function TreeEmpty() { return ( <Tree aria-label="Archived categories" variant="framed" emptyContent="No archived categories" nodes={[] as { id: string }[]} getKey={(category) => category.id} /> );}Search
query filters nodes by name. Every match keeps the branches above it, the matched text is marked, and the path to it is open while the query lasts. The set of branches the reader opened does not change, so clearing the field brings it back. The field is yours.
- Pantry
- Spices
- Ground spices
- Whole spices
import { useState } from 'react';import { Glyph, Icon } from '@slotted/react/icon';import { Stack } from '@slotted/react/stack';import { TextField } from '@slotted/react/text-field';import { Tree } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeFiltering() { const [query, setQuery] = useState('spice'); return ( <Stack gap={3}> <TextField aria-label="Find a category" clearable onValueChange={(next) => setQuery(next)} start={ <Icon> <Glyph name="search" /> </Icon> } type="search" value={query} /> <Tree aria-label="Product categories" emptyContent="No category matches" query={query} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> </Stack> );}Revealing a node
scrollToKey opens the branches above a node and scrolls to it. The second argument places it at the start, the center or the end, or moves as little as possible with nearest, the default.
- Warehouse CMH
- Aisle A
- Bin CMH-A-01
- Bin CMH-A-02
- Bin CMH-A-03
- Bin CMH-A-04
- Bin CMH-A-05
- Bin CMH-A-06
- Bin CMH-A-07
- Bin CMH-A-08
- Aisle B
- Aisle C
- Warehouse RNO
- Warehouse SAV
import { useRef, useState } from 'react';import { Button } from '@slotted/react/button';import { Stack } from '@slotted/react/stack';import { Tree, type TreeHandle, type TreeValue } from '@slotted/react/tree';interface Place { id: string; name: string; children?: Place[];}const PLACES: Place[] = ['CMH', 'RNO', 'SAV'].map((site) => ({ id: site, name: `Warehouse ${site}`, children: ['A', 'B', 'C'].map((aisle) => ({ id: `${site}-${aisle}`, name: `Aisle ${aisle}`, children: Array.from({ length: 8 }, (_, index) => ({ id: `${site}-${aisle}-0${index + 1}`, name: `Bin ${site}-${aisle}-0${index + 1}`, })), })),}));export default function TreeReveal() { const tree = useRef<TreeHandle>(null); const [value, setValue] = useState<TreeValue>(null); function handleFind() { setValue('SAV-B-06'); tree.current?.scrollToKey('SAV-B-06', 'center'); } return ( <Stack align="start" gap={3}> <Button size="sm" variant="outline" onClick={handleFind}> Find bin SAV-B-06 </Button> <Tree aria-label="Bins" handleRef={tree} onValueChange={(next) => setValue(next)} value={value} defaultExpandedKeys={['CMH', 'CMH-A']} nodes={PLACES} getKey={(place) => place.id} getLabel={(place) => place.name} getChildren={(place) => place.children} /> </Stack> );}Virtual scrolling
virtual renders only the rows in view, plus overscan rows on each side. Set itemSize to the row height in pixels. The rows are flat and state their own level, and the active node stays in the document while it is out of view. This tree holds 3,624 rows.
- 2025-01
- SO-10000
- SO-10001
- SO-10002
import { Tree } from '@slotted/react/tree';interface OrderNode { id: string; name: string; children?: OrderNode[];}const MONTHS: OrderNode[] = Array.from({ length: 24 }, (_, month) => { const id = `${2025 + Math.floor(month / 12)}-${String((month % 12) + 1).padStart(2, '0')}`; return { id, name: id, children: Array.from({ length: 150 }, (_entry, index) => ({ id: `${id}-${index}`, name: `SO-${10000 + month * 150 + index}`, })), };});export default function TreeVirtualization() { return ( <Tree aria-label="Orders by month" variant="framed" virtual itemSize={34} defaultExpandedKeys={MONTHS.map((month) => month.id)} nodes={MONTHS} getKey={(node) => node.id} getLabel={(node) => node.name} getChildren={(node) => node.children} /> );}In a form
In React, name renders one hidden input for each chosen key, so a native form carries the set. In Angular, the tree is the form control: bind formControlName or ngModel.
import { useState } from 'react';import type { SubmitEvent } from 'react';import { Button } from '@slotted/react/button';import { Inline } from '@slotted/react/inline';import { Stack } from '@slotted/react/stack';import { Tree } from '@slotted/react/tree';import { Text } from '@slotted/react/typography';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeForm() { const [saved, setSaved] = useState<string | null>(null); function handleSubmit(event: SubmitEvent<HTMLFormElement>) { event.preventDefault(); const chosen = new FormData(event.currentTarget).getAll('categories'); setSaved(`Submitted ${chosen.length} categories.`); } return ( <form onSubmit={handleSubmit}> <Stack gap={4}> <Tree aria-label="Categories in this feed" name="categories" selectionMode="multiple" defaultExpandedKeys={['beverages']} defaultValue={['coffee', 'tea']} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <Inline align="center" gap={3}> <Button type="submit">Save feed</Button> {saved && ( <Text size="sm" tone="muted"> {saved} </Text> )} </Inline> </Stack> </form> );}Defaults for an application
TreeDefaultsProvider in React and provideTreeDefaults in Angular set the axes once for every tree under them. A value set on a tree still wins: the second tree below turns its guides back on.
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Household
import { Grid } from '@slotted/react/grid';import { Tree, TreeDefaultsProvider } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];export default function TreeDefaultsExample() { return ( <TreeDefaultsProvider expandOn="expander" guides={false} size="sm"> <Grid columns={2} gap={6} minItemWidth="xs"> <Tree aria-label="Categories" defaultExpandedKeys={['beverages']} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <Tree aria-label="Categories with guides" guides defaultExpandedKeys={['beverages']} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> </Grid> </TreeDefaultsProvider> );}Recipe: a catalog browser
A tree filters the list beside it. expandOn="expander" lets a branch be chosen without closing it, and disallowEmptySelection keeps one category chosen. Choosing a branch lists the products of every category under it.
- Beverages
- Coffee
- Tea
- Soft drinks
- Pantry
- Oils and vinegars
- Spices
- Household
- House blend, 1 kgBEV-104
- Decaf espresso, 500 gBEV-131
- Earl grey, 50 bagsBEV-220
- Ginger ale, 24 cansBEV-305
import { useState } from 'react';import { Grid } from '@slotted/react/grid';import { List, ListEmpty } from '@slotted/react/list';import { ListItem, ListItemBody, ListItemContent, ListItemEnd, ListItemLabel,} from '@slotted/react/list-item';import { Tree } from '@slotted/react/tree';interface Category { id: string; name: string; children?: Category[];}const CATEGORIES: Category[] = [ { id: 'beverages', name: 'Beverages', children: [ { id: 'coffee', name: 'Coffee' }, { id: 'tea', name: 'Tea' }, { id: 'soft-drinks', name: 'Soft drinks' }, ], }, { id: 'pantry', name: 'Pantry', children: [ { id: 'oils', name: 'Oils and vinegars' }, { id: 'spices', name: 'Spices', children: [ { id: 'ground-spices', name: 'Ground spices' }, { id: 'whole-spices', name: 'Whole spices' }, ], }, ], }, { id: 'household', name: 'Household' },];const PRODUCTS = [ { sku: 'BEV-104', name: 'House blend, 1 kg', category: 'coffee' }, { sku: 'BEV-131', name: 'Decaf espresso, 500 g', category: 'coffee' }, { sku: 'BEV-220', name: 'Earl grey, 50 bags', category: 'tea' }, { sku: 'BEV-305', name: 'Ginger ale, 24 cans', category: 'soft-drinks' }, { sku: 'PAN-012', name: 'Olive oil, 5 L', category: 'oils' }, { sku: 'PAN-118', name: 'Smoked paprika, 250 g', category: 'ground-spices' },];function keysUnder(categories: Category[], key: string, inside = false): string[] { return categories.flatMap((category) => { const here = inside || category.id === key; return [...(here ? [category.id] : []), ...keysUnder(category.children ?? [], key, here)]; });}export default function TreeCatalog() { const [category, setCategory] = useState('beverages'); const keys = keysUnder(CATEGORIES, category); const products = PRODUCTS.filter((product) => keys.includes(product.category)); return ( <Grid columns={2} gap={6} minItemWidth="xs"> <Tree aria-label="Product categories" disallowEmptySelection expandOn="expander" defaultExpandedKeys={['beverages', 'pantry']} onValueChange={(next) => setCategory(String(next))} value={category} nodes={CATEGORIES} getKey={(category) => category.id} getLabel={(category) => category.name} getChildren={(category) => category.children} /> <List aria-label="Products" variant="framed"> {products.length === 0 && <ListEmpty>No products in this category</ListEmpty>} {products.map((product) => ( <ListItem key={product.sku}> <ListItemContent> <ListItemBody> <ListItemLabel>{product.name}</ListItemLabel> </ListItemBody> <ListItemEnd>{product.sku}</ListItemEnd> </ListItemContent> </ListItem> ))} </List> </Grid> );}Recipe: an access editor
The cascade, the search and a disabled permission together. The count reads the permissions and leaves out the branches that the cascade adds to the value.
- Orders
- View orders
- Edit orders
- Issue refunds
- Finance
- View invoices
- Approve payoutsOwners only
- Reports
import { useState } from 'react';import { Button } from '@slotted/react/button';import { Glyph, Icon } from '@slotted/react/icon';import { Inline } from '@slotted/react/inline';import { Stack } from '@slotted/react/stack';import { TextField } from '@slotted/react/text-field';import { Tree } from '@slotted/react/tree';import { Text } from '@slotted/react/typography';interface Scope { id: string; name: string; locked?: boolean; children?: Scope[];}const SCOPES: Scope[] = [ { id: 'orders', name: 'Orders', children: [ { id: 'orders.view', name: 'View orders' }, { id: 'orders.edit', name: 'Edit orders' }, { id: 'orders.refund', name: 'Issue refunds' }, ], }, { id: 'finance', name: 'Finance', children: [ { id: 'finance.invoices', name: 'View invoices' }, { id: 'finance.payouts', name: 'Approve payouts', locked: true }, ], }, { id: 'reports', name: 'Reports' },];export default function TreeAccessEditor() { const [query, setQuery] = useState(''); const [granted, setGranted] = useState<readonly string[]>(['orders.view', 'finance.invoices']); const [saved, setSaved] = useState(granted); const permissions = granted.filter((key) => key.includes('.') || key === 'reports').length; return ( <Stack gap={3}> <TextField aria-label="Find a permission" clearable onValueChange={(next) => setQuery(next)} start={ <Icon> <Glyph name="search" /> </Icon> } type="search" value={query} /> <Tree aria-label="Permissions of the support role" emptyContent="No permission matches" expandOn="expander" variant="framed" selectionCascade="descendants" selectionMode="multiple" defaultExpandedKeys={['orders', 'finance']} isNodeDisabled={(scope) => scope.locked === true} onValueChange={(next) => setGranted(next as readonly string[])} query={query} value={granted} renderCells={(scope) => ({ description: scope.locked ? 'Owners only' : undefined })} nodes={SCOPES} getKey={(scope) => scope.id} getLabel={(scope) => scope.name} getChildren={(scope) => scope.children} /> <Inline align="center" gap={3}> <Button disabled={saved === granted} onClick={() => setSaved(granted)}> Save role </Button> <Text role="status" size="sm" tone="muted"> {permissions} permissions granted </Text> </Inline> </Stack> );}Accessibility
| Key | Effect | Focus |
|---|---|---|
| Tab | moves into and out of the tree; the whole tree is one tab stop | the active node under roving, the canvas under activedescendant |
| ArrowRight | opens a closed branch; on an open branch moves into it; on a leaf does nothing | unchanged, then the first child |
| ArrowLeft | closes an open branch; on a leaf or a closed branch moves to the parent; at the root level does nothing | unchanged, then the parent |
| ArrowDown | moves to the next visible node without opening or closing anything | that node |
| ArrowUp | moves to the previous visible node without opening or closing anything | that node |
| Home | moves to the first visible node | that node |
| End | moves to the last visible node | that node |
| PageDown | moves ten visible nodes on, clamping at the end rather than wrapping | that node |
| PageUp | moves ten visible nodes back, clamping at the start | that node |
| Enter | activates the node; under expandOn=row a branch also toggles | unchanged |
| Space | toggles the selection of the active node | unchanged |
| Shift+ArrowDown | moves and toggles the selection of the node moved to, in multiple | the next visible node |
| Shift+ArrowUp | the same, backwards | the previous visible node |
| Shift+Space | selects from the anchor to the active node, in multiple | unchanged |
| Control+Shift+Home | selects from the active node to the first visible one, in multiple | unchanged |
| Control+Shift+End | selects from the active node to the last visible one, in multiple | unchanged |
| Control+A | selects every visible enabled node, or clears when they are already all selected, unless disallowSelectAll | unchanged |
| * | opens every sibling at the level of the active node | unchanged |
| a printable character | moves to the next visible node whose label starts with what has been typed | that node |
- The tree takes its accessible name from aria-label or aria-labelledby, which reach the element with role="tree".
- Each node is named by its own label through aria-labelledby. A treeitem contains its children, so a name computed from its contents would be everything under it.
- aria-expanded is written on branches and never on leaves, which would otherwise be announced as parents.
- Selection is stated with aria-selected under the highlight and with aria-checked under the checkbox, and never with both.
- aria-level, aria-setsize and aria-posinset are written while the rows are flat. A nested tree leaves them to the browser, except on the children of a branch that is still missing some of them.
- The whole tree is one tab stop. Focus lands on the chosen node when there is one and on the first node otherwise, and a virtual tree keeps the active node in the document.
- A control in the trailing cell of a row is a tab stop of its own and receives its own keys.
- A branch whose children are arriving has aria-busy, and a polite live region announces the branch and how many items arrived.
API
Tree
Props
valuestring | readonly string[] | null- The chosen key, or the set of chosen keys in multiple. When it is present the selection is controlled.
defaultValuestring | readonly string[] | null- The selection an uncontrolled tree starts with.
expandedKeysreadonly string[]- The keys of the open branches. When it is present the expansion is controlled. A query never changes it.
defaultExpandedKeysreadonly string[]- The branches an uncontrolled tree starts with open.
activeKeystring | null- The node the keyboard is on, which is separate from the selection. When it is present the position is controlled.
defaultActiveKeystring | null- The node the keyboard starts on in an uncontrolled tree.
size'sm' | 'md' | 'lg'Defaultmd- The row height, the type size, the glyph size and the indent, which move together.
variant'plain' | 'framed'Defaultplain- Whether the tree draws its own box. plain draws none and framed draws an edge, a radius and a shadow.
structure'auto' | 'nested' | 'flat'Defaultauto- Whether the nodes nest in groups or lie flat with their level stated. auto is flat while virtual and nested otherwise. Only a tree built from nodes can be flat.
selectionMode'none' | 'single' | 'multiple'Defaultsingle- How many nodes can be chosen at once. none writes no selection attribute on any node.
selectionBehavior'toggle' | 'replace'Defaulttoggle- What a plain press does. toggle changes one node and needs no modifier key; replace collapses the selection onto the node pressed, and Ctrl, Command and Shift extend it.
selectionIndicator'auto' | 'highlight' | 'checkbox' | 'none'Defaultauto- How the selection is drawn and which attribute states it. highlight writes aria-selected, checkbox writes aria-checked, and auto draws a checkbox in multiple and a highlight in single.
selectionCascade'none' | 'descendants'Defaultnone- Whether choosing a branch also chooses its enabled descendants. descendants needs nodes.
expandOn'row' | 'expander'Defaultrow- What opens a branch. row gives the whole row and the chevron that job; expander leaves it to the chevron alone.
focusMode'auto' | 'roving' | 'activedescendant'Defaultauto- How the position of the keyboard is expressed. auto is activedescendant while virtual and a roving tab stop otherwise.
guidesbooleanDefaulttrue- Whether the lines that tie a row to its parent are drawn.
loopbooleanDefaultfalse- Whether the arrow keys wrap past the first and the last node.
typeaheadbooleanDefaulttrue- Whether typing a name moves the keyboard to the node that starts with it.
typeaheadTimeoutnumberDefault500- The milliseconds of silence that start a new typeahead search.
selectOnFocusbooleanDefaultfalse- Whether moving the keyboard also chooses the node it lands on.
navigateDisabledbooleanDefaultfalse- Whether the arrow keys land on a disabled node.
disallowEmptySelectionbooleanDefaultfalse- Whether the last chosen node stays chosen when it is pressed again.
disallowSelectAllbooleanDefaultfalse- Whether Control+A is kept from choosing every visible node.
pageSizenumberDefault10- How many nodes Page Up and Page Down move by.
virtualbooleanDefaultfalse- Whether only the rows in view are rendered. It needs nodes and itemSize, and it lays the rows flat.
itemSizenumberDefault32- The height of one row in pixels, read while virtual.
overscannumberDefault4- How many rows are rendered on each side of the rows in view, while virtual.
disabledbooleanDefaultfalse- Whether the whole tree is disabled.
readOnlybooleanDefaultfalse- Whether the selection is fixed while the tree can still be opened and walked.
requiredbooleanDefaultfalse- Whether the tree states that a choice is required.
invalidbooleanDefaultfalse- Whether the tree is drawn and announced as being in error.
loadingbooleanDefaultfalse- Whether the nodes of the tree are still arriving. It writes aria-busy on the tree.
namestring- The form name. The tree renders one hidden input per chosen key under it.
nodesreadonly T[]- The hierarchy the tree renders. selectionCascade, expandAll, query and virtual read it.
getKey(node: T) => string- Returns the key of a node. It is required with nodes.
getLabel(node: T) => string- Returns the name of a node, which is what the row shows and what typeahead and query match.
getChildren(node: T) => readonly T[] | undefined- Returns the children of a node, for a nested hierarchy.
getLevel(node: T) => number- Returns the depth of a node, for nodes that arrive as a flat list in reading order.
hasChildren(node: T) => boolean- Returns whether a node is a branch before its children have arrived.
getChildrenCount(node: T) => number | undefined- Returns how many children a branch will have. Until all of them arrive, the ones present state the size of the whole set.
isNodeDisabled(node: T) => boolean- Returns whether a node is disabled.
isNodeLoading(node: T) => boolean- Returns whether the children of a node are arriving.
querystring- The text the tree filters nodes by. The field it is typed into is yours.
renderCells(node: T, key: string) => TreeNodeCells- Returns the icon, label, description, meta and actions of one row of nodes. A cell left out is not drawn, and a label left out is the name getLabel returns.
messagesPartialMessages<TreeMessages>- The words the tree announces, over the ones of the language in force.
emptyContentReactNode- What the tree shows when it holds no node or the query matches none.
render(props: TreeRootProps) => ReactNode- Renders the root as another element.
handleRefRef<TreeHandle>- The imperative handle: focus, scrollToKey, expand, collapse, expandAll, collapseAll, getActiveKey and getElement.
labelReactNode- On TreeNodeThe name of the node, which is also its accessible name.
descriptionReactNode- On TreeNodeA second, muted text after the name. It is hidden when the tree is narrower than 240 pixels.
iconReactNode- On TreeNodeThe leading icon. One node with an icon reserves the same cell on every row.
metaReactNode- On TreeNodeThe trailing count, size or badge.
actionsReactNode- On TreeNodeThe trailing controls. A press on one of them does not choose or open the row.
textValuestring- On TreeNodeThe text typeahead matches, for a label that is not plain text.
match'hit' | 'ancestor'- On TreeNodeWhether a query matched this node or one below it. The tree writes it on the rows of nodes; a tree you write by hand states it.
pinnedboolean- On TreeNodeWhether the node is placed outside the rows in view. The tree sets it while virtual.
offsetnumber- On TreeNodeWhere a pinned row sits, in pixels. The tree sets it while virtual.
depthnumber- On TreeNodeThe depth of the node in the flat structure. Elsewhere the markup states it.
Events
| Name | Payload | When |
|---|---|---|
onValueChange | (value: string | readonly string[] | null, request: ChangeRequest) | Before the selection changes. The value is one key, or the set in multiple. The request carries the previous value, the reason (pointer, keyboard, select, clear or programmatic), the originating event and cancel(). |
onExpandedKeysChange | (keys: readonly string[], request: ChangeRequest) | Before a branch opens or closes. The reasons are pointer, keyboard and programmatic. A query holds branches open without this event. |
onActiveKeyChange | (key: string | null, request: ChangeRequest) | Before the keyboard moves to another node. The reasons are pointer, keyboard and programmatic. Closing a branch that holds the active node emits this event first. |
onNodeActivate | (key: string, reason: 'pointer' | 'keyboard') | When a node is pressed, or Enter is pressed on it. Use it to open what the node stands for; it does not depend on the selection. |
Composition
TreeDefaultsProvider{ size, variant, expandOn, … }- On a subtreeSets the axes once for every tree under it. A prop on a tree still wins.
render(props) => ReactNode- On Tree, TreeNodeRenders the part as another element with the attributes and handlers it receives.
label, description, icon, meta, actionsReactNode- On TreeNodeThe cells of a row written by hand. Each takes any content.
handleRefRef<TreeHandle>- Reaches focus, scrollToKey, expand, collapse, expandAll, collapseAll, getActiveKey and getElement.
onClick(event: MouseEvent) => void- On TreeNodeRuns before the row acts, and preventDefault keeps the row from acting.
data-expanded, data-selected, data-loadingattribute- On the nodeThe state of a node in the DOM, which lets CSS change an icon by state.
Parts
| Part | Element | Required | Purpose |
|---|---|---|---|
root | div, or the element render returns | Yes | The box around the tree. It carries data-ui="tree" and every axis, it is the container the indent adapts to, and in the flat structure it is also the scroller. |
canvas | ul with role="tree" | Yes | The tree itself: the accessible name, aria-multiselectable and the single tab stop. While virtual it also holds the full height of the list. |
node | li with role="treeitem" | Yes | One node. It carries the key, the depth, aria-expanded on a branch and the selection attribute, and it is named by its own label, so a branch is not announced as everything under it. |
row | div | Yes | The line that is shown and pressed. It is separate from the node, which also contains the children, so a press on a child does not press its parent. |
guide | span | No | One line per ancestor level, under the chevron of that level. It is absent at the root level and when guides is false. |
expander | span | Yes | The chevron. It is not a button, because a tree has one tab stop. A leaf keeps the cell empty, so the names at one depth start in one column. |
indicator | span | No | The checkbox, under selectionIndicator="checkbox". The other indicators draw no cell. |
icon | span | No | The leading icon, which you supply. One node with an icon reserves the same cell on every row. |
label | span | Yes | The name. It names the node, it is what typeahead matches, and a long name truncates while staying whole in the DOM. |
description | span | No | A second, muted text after the name. It is hidden when the tree is narrower than 240 pixels. |
meta | span | No | The trailing count, size or badge. It keeps its own width, so a long name truncates before it. |
loader | span with data-ui="spinner" | No | The spinner of a branch whose children are arriving. It takes the cell and the size of the chevron, so nothing moves. |
actions | div | No | The trailing controls. They are always in the DOM, and the keys and clicks they receive are not the row's. |
group | ul with role="group" | No | The children of an open branch. A closed branch renders none. |
empty | div | No | What the tree shows when it holds no node or the query matches none. |
Theming
Each token is a CSS custom property: set it in a theme, or on any element to retune every tree inside it.
Tree tokens
| Token | Default |
|---|---|
--slotted-tree-border-color | var(--slotted-control-border-color) |
--slotted-tree-guide-color | color-mix(in oklab, var(--slotted-border-strong) 60%, var(--slotted-border-subtle)) |
--slotted-tree-highlight | var(--slotted-tone-secondary-subtle-hover) |
--slotted-tree-highlight-active | var(--slotted-tone-secondary-subtle-active) |
--slotted-tree-indent | calc(var(--_icon-size) / 2 + var(--slotted-space-4, 0.5rem)) |
--slotted-tree-mark-inset | 2px |
--slotted-tree-measure | 28rem |
--slotted-tree-padding-block | var(--slotted-space-2, 0.25rem) |
--slotted-tree-padding-inline | var(--slotted-space-2, 0.25rem) |
--slotted-tree-radius | var(--slotted-radius-md, 6px) |
--slotted-tree-rows | 12 |
--slotted-tree-selected-edge | var(--slotted-tone-accent-border) |
--slotted-tree-selected-surface | var(--slotted-tone-accent-surface) |
--slotted-tree-selected-text | var(--slotted-tone-accent-text) |
--slotted-tree-shadow | var(--slotted-control-shadow) |
--slotted-tree-surface | var(--slotted-surface, #ffffff) |
--slotted-tree-text | var(--slotted-text, #0f172a) |
--slotted-tree-text-muted | var(--slotted-text-muted, #5b6b7f) |
Theme tokens it reads
| Token | Default |
|---|---|
--slotted-border-strong | Set per scheme by the theme |
--slotted-border-subtle | Set per scheme by the theme |
--slotted-border-width-medium | 1.5px |
--slotted-border-width-thin | 1px |
--slotted-control-border-color | Set per scheme by the theme |
--slotted-control-font-size-lg | comfortable 14px · compact 13px · dense 12px |
--slotted-control-font-size-md | comfortable 13px · compact 12px · dense 12px |
--slotted-control-font-size-sm | comfortable 12px · compact 12px · dense 12px |
--slotted-control-gap-lg | comfortable 8px · compact 6px · dense 6px |
--slotted-control-gap-md | comfortable 8px · compact 6px · dense 4px |
--slotted-control-gap-sm | comfortable 6px · compact 4px · dense 4px |
--slotted-control-height-lg | comfortable 38px · compact 32px · dense 30px |
--slotted-control-height-md | comfortable 34px · compact 28px · dense 26px |
--slotted-control-height-sm | comfortable 30px · compact 26px · dense 24px |
--slotted-control-icon-size-lg | comfortable 18px · compact 16px · dense 14px |
--slotted-control-icon-size-md | comfortable 16px · compact 14px · dense 13px |
--slotted-control-icon-size-sm | comfortable 14px · compact 13px · dense 12px |
--slotted-control-invalid-edge-width | var(--slotted-border-width-thin) |
--slotted-control-padding-inline-lg | comfortable 16px · compact 12px · dense 10px |
--slotted-control-padding-inline-md | comfortable 13px · compact 10px · dense 8px |
--slotted-control-padding-inline-sm | comfortable 10px · compact 8px · dense 6px |
--slotted-control-shadow | Set per scheme by the theme |
--slotted-control-transition-duration | var(--slotted-duration-short) |
--slotted-control-transition-easing | var(--slotted-easing-standard) |
--slotted-disabled-background | Set per scheme by the theme |
--slotted-disabled-border | Set per scheme by the theme |
--slotted-disabled-foreground | Set per scheme by the theme |
--slotted-duration-medium | 200ms |
--slotted-duration-short | 120ms |
--slotted-easing-standard | cubic-bezier(0.2, 0, 0, 1) |
--slotted-focus-ring-color | Set per scheme by the theme |
--slotted-focus-ring-color-invalid | Set per scheme by the theme |
--slotted-focus-ring-width | var(--slotted-border-width-thick) |
--slotted-font-family-sans | 'Geist Variable', ui-sans-serif, system-ui, sans-serif |
--slotted-font-size-xs | 0.75rem |
--slotted-font-weight-semibold | 600 |
--slotted-highlight-tint-opacity | 0.075 |
--slotted-line-height-sm | 1.45 |
--slotted-radius-md | 6px |
--slotted-radius-xs | 2px |
--slotted-selection-size-lg | 18px |
--slotted-selection-size-md | 16px |
--slotted-selection-size-sm | 14px |
--slotted-space-1 | 0.125rem |
--slotted-space-2 | 0.25rem |
--slotted-space-3 | 0.375rem |
--slotted-space-4 | 0.5rem |
--slotted-space-5 | 0.75rem |
--slotted-surface | Set per scheme by the theme |
--slotted-target-min | 24px |
--slotted-text | Set per scheme by the theme |
--slotted-text-muted | Set per scheme by the theme |
--slotted-tone-accent-border | Set per scheme by the theme |
--slotted-tone-accent-on-solid | Set per scheme by the theme |
--slotted-tone-accent-solid | Set per scheme by the theme |
--slotted-tone-accent-surface | Set per scheme by the theme |
--slotted-tone-accent-text | Set per scheme by the theme |
--slotted-tone-danger-border | Set per scheme by the theme |
--slotted-tone-secondary-subtle-active | Set per scheme by the theme |
--slotted-tone-secondary-subtle-hover | Set per scheme by the theme |