Components
Tree
A hierarchy of items that open and close, such as files and folders, with selection and keyboard support.
Introduction
A tree shows things that live inside other things: files in folders, pages in sections, categories in categories. Each level can be opened to show its children and closed to hide them, so a large hierarchy stays easy to scan.
- Built on react-aria's Tree: one tab stop, the arrow keys to move, open and close, typeahead, and the treegrid role for screen readers.
- Selection of one or several items, with checkboxes for several. Open and closed state can be left to the tree or controlled by you.
- An icon (that can change when open), a badge and an action or link per item, and three sizes.
For the main navigation of an app, use Sidebar. Use a tree when the user needs to see and pick from a hierarchy.
Installation
centerUI has no CLI or registry yet: components are copied into your project. Tree uses Checkbox for multiple selection, so it needs everything Checkbox needs.
# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx
# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx
# npm
npm install react-aria-components tailwind-variants tailwind-merge clsxAdd Checkbox first (see its Manual installation), then follow the steps below.
Manual installation
Copy these files into your project and keep the paths, or adjust the imports.
1. Add the styles
src/types/tree-styles.tsShow code
import { tv } from "tailwind-variants";
export const treeStyles = tv({
slots: {
root: "flex flex-col gap-0.5 p-1 text-fg outline-none",
// One row. It is the row that is hovered, focused and selected; the content
// inside it is indented to show how deep the item is.
item: [
"group/tree-item relative flex cursor-default items-center rounded-md px-1.5 text-sm outline-none transition-colors",
"data-hovered:bg-muted",
"data-focus-visible:ring-2 data-focus-visible:ring-ring data-focus-visible:ring-inset",
"data-selected:bg-secondary data-selected:font-medium data-selected:text-secondary-fg",
"data-disabled:cursor-not-allowed data-disabled:opacity-50",
],
content: "flex w-full min-w-0 items-center gap-1.5",
chevron: [
"flex size-5 shrink-0 items-center justify-center rounded text-muted-fg outline-none transition-colors",
"hover:text-fg",
"[&_svg]:size-3.5 [&_svg]:transition-transform",
"group-data-expanded/tree-item:[&_svg]:rotate-90",
],
icon: "flex shrink-0 items-center text-muted-fg [&_svg]:size-4",
label: "min-w-0 flex-1 truncate",
badge:
"ml-auto shrink-0 rounded-full bg-secondary px-1.5 text-xs font-medium text-secondary-fg group-data-selected/tree-item:bg-bg/60",
empty: "px-3 py-6 text-center text-sm text-muted-fg",
},
variants: {
variant: {
plain: {},
outline: { root: "rounded-lg border bg-card" },
},
size: {
sm: { item: "h-7" },
md: { item: "h-8" },
lg: { item: "h-10 text-base", icon: "[&_svg]:size-5" },
},
},
defaultVariants: { variant: "plain", size: "md" },
});2. Add the Tree file
src/components/ui/tree/tree.tsxShow code
"use client";
import { createContext, type ReactNode, useContext } from "react";
import {
Button as AriaButton,
Tree as AriaTree,
TreeItem as AriaTreeItem,
type TreeItemProps as AriaTreeItemProps,
type TreeProps as AriaTreeProps,
TreeItemContent,
} from "react-aria-components";
import { ChevronRightIcon } from "@/components/icons";
import { Checkbox } from "@/components/ui/checkbox/checkbox";
import { cn } from "@/lib/cn";
import { cx } from "@/lib/primitive";
import { treeStyles } from "@/types/tree-styles";
// How far each level is pushed in, and what the tree looks like, for the items.
const indent = 16;
interface TreeContextValue {
size: "sm" | "md" | "lg";
showCheckboxes: boolean;
}
const TreeContext = createContext<TreeContextValue>({
size: "md",
showCheckboxes: true,
});
export interface TreeProps<T extends object>
extends Omit<AriaTreeProps<T>, "className"> {
/** A frame around the tree, or none. */
variant?: "plain" | "outline";
size?: "sm" | "md" | "lg";
/** With `selectionMode="multiple"`: show a checkbox before each item. Defaults to `true`. */
showCheckboxes?: boolean;
/** Names the tree for screen readers. */
"aria-label"?: string;
className?: string;
}
/**
* A hierarchy of items that can be opened and closed, such as files and folders
* or a menu of sections. Built on react-aria's Tree, so the arrow keys move
* through the rows (Right opens, Left closes), typing jumps to an item, Space
* selects, and Enter runs the item's action. Give it an `aria-label`.
*
* Nest `TreeItem`s inside a `TreeItem` to make its children. Set
* `selectionMode` to let the user pick one or several items, and
* `expandedKeys` (or `defaultExpandedKeys`) to control which are open.
*
* @example
* <Tree aria-label="Files" defaultExpandedKeys={["src"]}>
* <TreeItem id="src" title="src" icon={<FolderIcon />}>
* <TreeItem id="app" title="app.tsx" icon={<FileIcon />} />
* </TreeItem>
* </Tree>
*/
export function Tree<T extends object>({
variant,
size = "md",
showCheckboxes = true,
className,
...props
}: TreeProps<T>) {
const styles = treeStyles({ variant, size });
return (
<TreeContext.Provider value={{ size, showCheckboxes }}>
<AriaTree
{...props}
className={cn(styles.root(), className)}
renderEmptyState={
props.renderEmptyState ??
(() => <p className={styles.empty()}>Nothing here.</p>)
}
/>
</TreeContext.Provider>
);
}
export interface TreeItemProps
extends Omit<
AriaTreeItemProps,
"children" | "className" | "title" | "textValue"
> {
/** The label of the item. A string also becomes its `textValue`, for typeahead. */
title: ReactNode;
/** The text typeahead matches. Needed when `title` is not a string. */
textValue?: string;
/** An icon before the label. */
icon?: ReactNode;
/** Shown instead of `icon` while the item is open, such as an open folder. */
expandedIcon?: ReactNode;
/** A short value at the end, such as a count. */
badge?: ReactNode;
className?: string;
/** Items nested in this one. */
children?: ReactNode;
}
/**
* One item of a `Tree`. Give it child `TreeItem`s and it gets a chevron to open
* and close them. `id` is the key that `selectedKeys` and `expandedKeys` use.
* Pass `href` to make it a link, or `onAction` to run something when it is
* pressed.
*/
export function TreeItem({
title,
icon,
expandedIcon,
badge,
className,
children,
textValue,
...props
}: TreeItemProps) {
const { size, showCheckboxes } = useContext(TreeContext);
const styles = treeStyles({ size });
return (
<AriaTreeItem
{...props}
textValue={textValue ?? (typeof title === "string" ? title : "")}
className={cx(styles.item(), className)}
>
<TreeItemContent>
{({ level, hasChildItems, isExpanded, selectionMode }) => (
<div
className={styles.content()}
style={{ paddingInlineStart: `${(level - 1) * indent}px` }}
>
{selectionMode === "multiple" && showCheckboxes ? (
<Checkbox slot="selection" size="sm" />
) : null}
{hasChildItems ? (
<AriaButton slot="chevron" className={styles.chevron()}>
<ChevronRightIcon />
</AriaButton>
) : (
// Keeps the labels of items without children lined up with the rest.
<span aria-hidden="true" className="size-5 shrink-0" />
)}
{icon || expandedIcon ? (
<span className={styles.icon()}>
{isExpanded && expandedIcon ? expandedIcon : icon}
</span>
) : null}
<span className={styles.label()}>{title}</span>
{badge !== undefined && badge !== null ? (
<span className={styles.badge()}>{badge}</span>
) : null}
</div>
)}
</TreeItemContent>
{children}
</AriaTreeItem>
);
}It imports ChevronRightIcon from @/components/icons. Add that icon, or swap it for your own.
3. Use it
import { Tree, TreeItem } from "@/components/ui/tree/tree";Anatomy
A tree is rows inside rows: each TreeItem holds its children.
<Tree aria-label="Files" defaultExpandedKeys={["src"]}>
<TreeItem id="src" title="src" icon={<FolderIcon />}>
<TreeItem id="app" title="app.tsx" icon={<FileIcon />} badge="M" />
</TreeItem>
<TreeItem id="readme" title="README.md" icon={<FileIcon />} />
</Tree>| Part | Rendered as | Notes |
|---|---|---|
| Tree | div, role=treegrid | The whole hierarchy. One stop in the tab order, with the arrow keys between rows. |
| TreeItem | div, role=row | One row. It is hovered, focused and selected as a whole, and indented by its depth. |
| Chevron | Button | Opens and closes an item that has children. Items without children get an empty space, so labels line up. |
| Checkbox | Checkbox | With multiple selection: one before each item. |
| Icon | svg | Before the label. It can change when the item is open. |
| Label | span | The title, cut with an ellipsis when it is too long. |
| Badge | span | A short value at the end, such as a count or a status. |
Give the tree an aria-label so a screen reader can name it.
Keyboard
The tree is one tab stop. Once it has focus, these keys work.
| Key | What it does |
|---|---|
| Arrow Down, Arrow Up | Move to the next or previous row |
| Arrow Right | Open the item, if it has children and is closed |
| Arrow Left | Close the item, or move to its parent when it is closed |
| Space | Select or deselect the item (with a selectionMode) |
| Enter | Run the item's action or follow its link |
| Type a letter | Jump to the next item whose title starts with it |
Examples
Click a chevron to open a folder, or use the arrow keys.
Usage
Icons
icon goes before the label. expandedIcon replaces it while the item is open, for an open folder.
From data
A tree is recursive, so build it from data with a component that renders itself. The previews on this page do exactly this.
const files = [
{ id: "src", name: "src", children: [{ id: "app", name: "app.tsx" }] },
{ id: "package", name: "package.json" },
];
// A tree is recursive, so a component that renders itself builds it from data.
function Items({ nodes }) {
return nodes.map((node) => (
<TreeItem key={node.id} id={node.id} title={node.name}
icon={node.children ? <FolderIcon /> : <FileIcon />}>
{node.children ? <Items nodes={node.children} /> : null}
</TreeItem>
));
}
<Tree aria-label="Files"><Items nodes={files} /></Tree>Single selection
selectionMode=“single” lets the user pick one item. Keep the selection in your own state with selectedKeys and onSelectionChange.
selected: page
Multiple selection
selectionMode=“multiple” adds a checkbox before each item, and Space toggles the item that has focus. Set showCheckboxes to false to select by clicking the row alone.
selected: button, select
Controlled expansion
Which items are open is the tree's own state, unless you keep it with expandedKeys and onExpandedChange. defaultExpandedKeys only sets the start.
open: src
Actions and links
onAction on the tree, or on an item, runs when Enter is pressed on it, or when it is clicked in a tree with no selection. An item with href is a link.
Press Enter on a file.
Disabled items
disabledKeys, or isDisabled on an item, makes it unavailable: it cannot be selected or acted on.
Badges
A short value at the end of the row, such as a count.
Sizes
Variants
A frame around the tree, or none when it sits inside something that already has one.
Empty state
A tree with no items shows a message. Give renderEmptyState your own to change it.
No files yet.
Component API
Tree and TreeItem take the props below, plus the rest of what the react-aria Tree and TreeItem accept.
Tree
| Prop | Type | Default |
|---|---|---|
| aria-label | string | - (give it one) |
| selectionMode | "none" | "single" | "multiple" | "none" |
| selectedKeys | Selection | - |
| defaultSelectedKeys | Selection | - |
| onSelectionChange | (keys: Selection) => void | - |
| disallowEmptySelection | boolean | false |
| expandedKeys | Iterable<Key> | - |
| defaultExpandedKeys | Iterable<Key> | - |
| onExpandedChange | (keys: Set<Key>) => void | - |
| disabledKeys | Iterable<Key> | - |
| onAction | (key: Key) => void | - |
| renderEmptyState | () => ReactNode | "Nothing here." |
| size | "sm" | "md" | "lg" | "md" |
| variant | "plain" | "outline" | "plain" |
| showCheckboxes | boolean | true |
TreeItem
| Prop | Type | Default |
|---|---|---|
| id | Key | - (required) |
| title | ReactNode | - (required) |
| textValue | string | the title, if it is a string |
| icon | ReactNode | - |
| expandedIcon | ReactNode | - |
| badge | ReactNode | - |
| href | string | - |
| onAction | () => void | - |
| isDisabled | boolean | false |
| children | TreeItem elements | - |