A tree view provides users with a way to navigate nested hierarchical information.
Content
TreeView follows the Collection Components API, accepting both static and dynamic collections. This example shows a dynamic collection, passing a list of objects to the items prop, and a recursive function to render the children.
import {TreeView, TreeViewItem, TreeViewItemContent, Collection} from '@react-spectrum/s2/TreeView';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
<TreeView
aria-label="Files"
styles={style({width: 'full'})}
defaultExpandedKeys={[1, 4]}
items={items}
selectionMode="multiple">
{function renderItem(item) {
return (
<TreeViewItem textValue={item.title}>
<TreeViewItemContent>{item.title}</TreeViewItemContent>
{/* recursively render children */}
<Collection items={item.children}>
{renderItem}
</Collection>
</TreeViewItem>
);
}}
</TreeView>
Slots
TreeViewItemContent supports icons, Text, ActionMenu, and ActionButtonGroup as children.
import {TreeView, TreeViewItem, TreeViewItemContent, Collection, Text} from '@react-spectrum/s2/TreeView';
import {ActionMenu, MenuItem} from '@react-spectrum/s2/ActionMenu';
import Folder from '@react-spectrum/s2/icons/Folder';
import File from '@react-spectrum/s2/icons/File';
import Edit from '@react-spectrum/s2/icons/Edit';
import Delete from '@react-spectrum/s2/icons/Delete';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
<TreeView
aria-label="Files"
styles={style({width: 'full'})}
defaultExpandedKeys={[1, 4]}
items={items}
selectionMode="multiple">
{function renderItem(item) {
return (
<TreeViewItem textValue={item.title}>
<TreeViewItemContent>
{item.type === 'directory' ? <Folder /> : <File />}
<Text>{item.title}</Text>
<ActionMenu>
<MenuItem>
<Edit />
<Text>Edit</Text>
</MenuItem>
<MenuItem>
<Delete />
<Text>Delete</Text>
</MenuItem>
</ActionMenu>
</TreeViewItemContent>
<Collection items={item.children}>
{renderItem}
</Collection>
</TreeViewItem>
);
}}
</TreeView>
Asynchronous loading
Use renderEmptyState to display a spinner during initial load. To enable infinite scrolling, render a <TreeViewLoadMoreItem> at the end of each <TreeViewItem>.
import {TreeView, TreeViewItem, TreeViewItemContent, TreeViewLoadMoreItem, Collection} from '@react-spectrum/s2/TreeView';
import {useAsyncList} from '@react-spectrum/s2/useAsyncList';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
interface Character {
name: string
}
function AsyncLoadingExample() {
return (
<TreeView
aria-label="Async loading tree"
styles={style({height: 300, width: 'full'})}>
<TreeViewItem textValue="Pokemon">
<TreeViewItemContent>Pokemon</TreeViewItemContent>
<Collection items={pokemonList.items}>
{(item) => (
<TreeViewItem id={item.name} textValue={item.name}>
<TreeViewItemContent>{item.name}</TreeViewItemContent>
</TreeViewItem>
)}
</Collection>
<TreeViewLoadMoreItem
onLoadMore={pokemonList.loadMore}
loadingState={pokemonList.loadingState} />
</TreeViewItem>
<TreeViewItem textValue="Star Wars">
<TreeViewItemContent>Star Wars</TreeViewItemContent>
<Collection items={starWarsList.items}>
{(item) => (
<TreeViewItem id={item.name} textValue={item.name}>
<TreeViewItemContent>{item.name}</TreeViewItemContent>
</TreeViewItem>
)}
</Collection>
<TreeViewLoadMoreItem
onLoadMore={starWarsList.loadMore}
loadingState={starWarsList.loadingState} />
</TreeViewItem>
</TreeView>
);
}
Links
Use the href prop on a <TreeItem> to create a link. See the getting started guide to learn how to integrate with your framework.
import {TreeView, TreeViewItem, TreeViewItemContent} from '@react-spectrum/s2/TreeView';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
<TreeView
aria-label="TreeView with links"
selectionMode="multiple"
styles={style({width: 'full'})}
defaultExpandedKeys={['bulbasaur', 'ivysaur']}>
<TreeViewItem
href="https://pokemondb.net/pokedex/bulbasaur"
target="_blank"
id="bulbasaur"
textValue="Bulbasaur">
<TreeViewItemContent>Bulbasaur</TreeViewItemContent>
<TreeViewItem
id="ivysaur"
href="https://pokemondb.net/pokedex/ivysaur"
target="_blank"
textValue="Ivysaur">
<TreeViewItemContent>Ivysaur</TreeViewItemContent>
<TreeViewItem
id="venusaur"
textValue="Venusaur"
href="https://pokemondb.net/pokedex/venusaur"
target="_blank">
<TreeViewItemContent>Venusaur</TreeViewItemContent>
</TreeViewItem>
</TreeViewItem>
</TreeViewItem>
</TreeView>
Empty state
Use renderEmptyState to render placeholder content when the tree is empty.
No results
import {TreeView} from '@react-spectrum/s2/TreeView';
import {IllustratedMessage, Heading, Content} from '@react-spectrum/s2/IllustratedMessage';
import {Link} from '@react-spectrum/s2/Link';
import FolderOpen from '@react-spectrum/s2/illustrations/linear/FolderOpen';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
<TreeView
aria-label="Search results"
styles={style({width: 'full'})}
renderEmptyState={() => (
<IllustratedMessage>
<FolderOpen />
<Heading>No results</Heading>
<Content>Press <Link href="https://adobe.com">here</Link> for more info.</Content>
</IllustratedMessage>
)}>
{[]}
</TreeView>
Selection and actions
Use the selectionMode prop to enable single or multiple selection. The selected items can be controlled via the selectedKeys prop, matching the id prop of the items. Return an ActionBar from renderActionBar to handle bulk actions, and use onAction for item navigation. Items can be disabled with the isDisabled prop. See the selection guide for more details.
Current selection:
Keyboard navigation
By default, TreeView uses arrow key navigation to move focus into rows. Set keyboardNavigationBehavior="tab" to have Tab move focus in and out of a row.
Use this when rows contain interactive elements such as text fields, where arrow keys and typing in the field should not trigger grid navigation or selection.
import {Text} from '@react-spectrum/s2';
import {TreeView, TreeViewItem, TreeViewItemContent} from '@react-spectrum/s2/TreeView';
import {TextField} from '@react-spectrum/s2/TextField';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
<TreeView
keyboardNavigationBehavior="tab"
selectionMode="multiple"
defaultExpandedKeys={['documents', 'photos']}
aria-label="Shared files"
styles={style({height: 250, width: 'full', maxWidth: 400})}>
<TreeViewItem id="documents" textValue="Documents">
<TreeViewItemContent>
<Text>
<TextField styles={style({margin: 4})} aria-label="title" defaultValue="Documents" placeholder="Enter name" />
</Text>
</TreeViewItemContent>
<TreeViewItem id="weekly" textValue="Weekly Report.pdf">
<TreeViewItemContent>
<Text>
<TextField styles={style({margin: 4})} aria-label="title" defaultValue="Weekly Report.pdf" placeholder="Enter name" />
</Text>
</TreeViewItemContent>
</TreeViewItem>
<TreeViewItem id="budget" textValue="Budget.xlsx">
<TreeViewItemContent>
<Text>
<TextField styles={style({margin: 4})} aria-label="title" defaultValue="Budget.xlsx" placeholder="Enter name" />
</Text>
</TreeViewItemContent>
</TreeViewItem>
</TreeViewItem>
<TreeViewItem id="photos" textValue="Photos">
<TreeViewItemContent>
<Text>
<TextField styles={style({margin: 4})} aria-label="title" defaultValue="Photos" placeholder="Enter name" />
</Text>
</TreeViewItemContent>
<TreeViewItem id="sunset" textValue="Sunset.jpg">
<TreeViewItemContent>
<Text>
<TextField styles={style({margin: 4})} aria-label="title" defaultValue="Sunset.jpg" placeholder="Enter name" />
</Text>
</TreeViewItemContent>
</TreeViewItem>
</TreeViewItem>
</TreeView>
Drag and drop
TreeView supports drag and drop interactions when the dragAndDropHooks prop is provided using the useDragAndDrop hook. Users can drop data on the tree as a whole, on individual items, insert new items between existing ones, or reorder items. React Spectrum supports drag and drop via mouse, touch, keyboard, and screen reader interactions. See the drag and drop guide to learn more.
If items contain interactive elements such as text fields, set pointerDragSource: 'handle' to restrict mouse and touch dragging to the drag handle. The handle is shown when an item is selected, hovered, or has keyboard focus within it, and is always shown on touch devices.
You can customize the drag preview by passing DragPreview or your own custom drag preview element to useDragAndDrop's renderDragPreview. DragPreview supports leading icons and Text with label and description slots.
import {Text} from '@react-spectrum/s2';
import {TreeView, TreeViewItem, TreeViewItemContent} from '@react-spectrum/s2/TreeView';
import {style} from '@react-spectrum/s2/style' with {type: 'macro'};
import {DragPreview, useDragAndDrop} from '@react-spectrum/s2/useDragAndDrop';
import {useTreeData} from '@react-spectrum/s2/useTreeData';
import {Collection} from '@react-spectrum/s2';
import Folder from '@react-spectrum/s2/icons/Folder';
import File from '@react-spectrum/s2/icons/File';
function ReorderableTree() {
let tree = useTreeData({
initialItems: [
{id: '1', title: 'Documents', children: [
{id: '2', title: 'Project', children: [
{id: '3', title: 'Weekly Report', children: []},
{id: '4', title: 'Budget', children: []}
]}
]},
{id: '5', title: 'Photos', children: [
{id: '6', title: 'Image 1', children: []},
{id: '7', title: 'Image 2', children: []}
]}
]
});
let {dragAndDropHooks} = useDragAndDrop({
getItems: (keys, items: typeof tree.items) => items.map(item => ({'text/plain': item.value.title, numChildren: (item.value.children.length).toString()})),
onMove(e) {
if (e.target.dropPosition === 'before') {
tree.moveBefore(e.target.key, e.keys);
} else if (e.target.dropPosition === 'after') {
tree.moveAfter(e.target.key, e.keys);
} else if (e.target.dropPosition === 'on') {
let targetNode = tree.getItem(e.target.key);
if (targetNode) {
let targetIndex = targetNode.children ? targetNode.children.length : 0;
let keyArray = Array.from(e.keys);
for (let i = 0; i < keyArray.length; i++) {
tree.move(keyArray[i], e.target.key, targetIndex + i);
}
}
}
},
renderDragPreview: (items) => (
<DragPreview items={items}>
{items[0].numChildren !== '0' ? <Folder /> : <File />}
<Text>{items[0]['text/plain']}</Text>
{items[0].numChildren !== '0' && (
<Text slot="description">{`${items[0].numChildren} item(s)`}</Text>
)}
</DragPreview>
)
});
return (
<TreeView
aria-label="Tree with hierarchical drag and drop"
selectionMode="multiple"
items={tree.items}
dragAndDropHooks={dragAndDropHooks}
styles={style({width: 'full', maxWidth: 320})}>
{function renderItem(item) {
return (
<TreeViewItem id={item.key} textValue={item.value.title}>
<TreeViewItemContent>
{item.children && item.children.length > 0 ? <Folder /> : <File />}
<Text>{item.value.title}</Text>
</TreeViewItemContent>
{item.children && <Collection items={item.children}>
{renderItem}
</Collection>}
</TreeViewItem>
);
}}
</TreeView>
);
}
API
<TreeView>
<TreeViewItem>
<TreeViewItemContent>
<Icon />
<Text />
<ActionMenu /> or <ActionButtonGroup />
</TreeViewItemContent>
<TreeViewItem>
{/* ... */}
</TreeViewItem>
<TreeViewLoadMoreItem />
</TreeViewItem>
</TreeView>
TreeView
| Name | Type | Default |
|---|---|---|
styles | StylesPropWithHeight | Default: — |
Spectrum-defined styles, returned by the | ||
dragAndDropHooks | DragAndDropHooks | Default: — |
The drag and drop hooks returned by | ||
keyboardNavigationBehavior | 'arrow' | 'tab' | Default: 'arrow'
|
Whether keyboard navigation to focusable elements within grid list items is via the left/right arrow keys or the tab key. | ||
expandedKeys | Iterable | Default: — |
The currently expanded keys in the collection (controlled). | ||
defaultExpandedKeys | Iterable | Default: — |
The initial expanded keys in the collection (uncontrolled). | ||
renderActionBar | | Default: — |
Provides the ActionBar to display when items are selected in the TreeView. | ||
selectionStyle | 'highlight' | 'checkbox' | Default: 'checkbox'
|
How selection should be displayed. For guidance on when to use which option, refer to the Spectrum page. | ||
children | ReactNode | | Default: — |
The contents of the collection. | ||
items | Iterable | Default: — |
Item objects in the collection. | ||
renderEmptyState | | Default: — |
Provides content to display when there are no items in the list. | ||
dependencies | ReadonlyArray | Default: — |
Values that should invalidate the item cache when using dynamic collections. | ||
selectionMode | SelectionMode | Default: — |
The type of selection that is allowed in the collection. | ||
selectedKeys | 'all' | Iterable | Default: — |
The currently selected keys in the collection (controlled). | ||
defaultSelectedKeys | 'all' | Iterable | Default: — |
The initial selected keys in the collection (uncontrolled). | ||
onSelectionChange | | Default: — |
Handler that is called when the selection changes. | ||
disabledKeys | Iterable | Default: — |
The item keys that are disabled. These items cannot be selected, focused, or otherwise interacted with. | ||
disabledBehavior | DisabledBehavior | Default: 'all'
|
Whether | ||
disallowEmptySelection | boolean | Default: — |
Whether the collection allows empty selection. | ||
shouldSelectOnPressUp | boolean | Default: — |
Whether selection should occur on press up instead of press down. | ||
escapeKeyBehavior | 'clearSelection' | 'none' | Default: 'clearSelection'
|
Whether pressing the escape key should clear selection in the grid list or not. Most experiences should not modify this option as it eliminates a keyboard user's ability to easily clear selection. Only use if the escape key is being handled externally or should not trigger selection clearing contextually. | ||
onAction | | Default: — |
Handler that is called when a user performs an action on an item. The exact user event depends
on the collection's | ||
onExpandedChange | | Default: — |
Handler that is called when items are expanded or collapsed. | ||
autoFocus | boolean | FocusStrategy | Default: — |
Whether to auto focus the gridlist or an option. | ||
id | string | Default: — |
The element's unique identifier. See MDN. | ||
aria-label | string | Default: — |
Defines a string value that labels the current element. | ||
aria-labelledby | string | Default: — |
Identifies the element (or elements) that labels the current element. | ||
aria-describedby | string | Default: — |
Identifies the element (or elements) that describes the object. | ||
aria-details | string | Default: — |
Identifies the element (or elements) that provide a detailed, extended description for the object. | ||
UNSAFE_className | UnsafeClassName | Default: — |
Sets the CSS className
for the element. Only use as a last resort. Use the | ||
UNSAFE_style | CSSProperties | Default: — |
Sets inline style for the
element. Only use as a last resort. Use the | ||
slot | string | null | Default: — |
A slot name for the component. Slots allow the component to receive props from a parent
component. An explicit | ||
TreeViewItem
| Name | Type | Default |
|---|---|---|
hasChildItems | boolean | Default: — |
Whether this item has children, even if not loaded yet. | ||
id | Key | Default: — |
The unique id of the tree row. | ||
value | T | Default: — |
The object value that this tree item represents. When using dynamic collections, this is set automatically. | ||
textValue | string | Default: — |
A string representation of the tree item's contents, used for features like typeahead. | ||
children | ReactNode | Default: — |
The content of the tree item along with any nested children. Supports static nested tree items or use of a Collection to dynamically render nested tree items. | ||
isDisabled | boolean | Default: — |
Whether the item is disabled. | ||
focusMode | 'child' | 'row' | Default: 'row'
|
Whether the row or its first focusable child element should be focused when the row is focused. | ||
allowsArrowNavigation | boolean | Default: — |
Whether the row should support arrow key navigation even when the containing collection uses tab keyboard navigation. Allows users to navigate between rows with arrow keys while focus is on an interactive child element within the row. | ||
onAction | | Default: — |
Handler that is called when a user performs an action on this tree item. The exact user event
depends on the collection's | ||
onHoverStart | | Default: — |
Handler that is called when a hover interaction starts. | ||
onHoverEnd | | Default: — |
Handler that is called when a hover interaction ends. | ||
onHoverChange | | Default: — |
Handler that is called when the hover state changes. | ||
onPress | | Default: — |
Handler that is called when the press is released over the target. | ||
onPressStart | | Default: — |
Handler that is called when a press interaction starts. | ||
onPressEnd | | Default: — |
Handler that is called when a press interaction ends, either over the target or when the pointer leaves the target. | ||
onPressChange | | Default: — |
Handler that is called when the press state changes. | ||
onPressUp | | Default: — |
Handler that is called when a press is released over the target, regardless of whether it started on the target or not. | ||
onFocus | | Default: — |
Handler that is called when the element receives focus. | ||
onBlur | | Default: — |
Handler that is called when the element loses focus. | ||
onFocusChange | | Default: — |
Handler that is called when the element's focus status changes. | ||
href | Href | Default: — |
A URL to link to. See MDN. | ||
hrefLang | string | Default: — |
Hints at the human language of the linked URL. SeeMDN. | ||
target | HTMLAttributeAnchorTarget | Default: — |
The target window for the link. See MDN. | ||
rel | string | Default: — |
The relationship between the linked resource and the current page. See MDN. | ||
download | boolean | string | Default: — |
Causes the browser to download the linked URL. A string may be provided to suggest a file name. See MDN. | ||
ping | string | Default: — |
A space-separated list of URLs to ping when the link is followed. See MDN. | ||
referrerPolicy | HTMLAttributeReferrerPolicy | Default: — |
How much of the referrer to send when following the link. See MDN. | ||
routerOptions | RouterOptions | Default: — |
Options for the configured client side router. | ||
aria-label | string | Default: — |
An accessibility label for this tree item. | ||
TreeViewItemContent
| Name | Type | |
|---|---|---|
children | ReactNode | |
Rendered contents of the tree item or child items. | ||
TreeViewLoadMoreItem
| Name | Type | |
|---|---|---|
loadingState | LoadingState | |
The current loading state of the TreeView or TreeView row. | ||
onLoadMore | | |
Handler that is called when more items should be loaded, e.g. while scrolling near the bottom. | ||