Menu

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 clsx

Add 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>
PartRendered asNotes
Treediv, role=treegridThe whole hierarchy. One stop in the tab order, with the arrow keys between rows.
TreeItemdiv, role=rowOne row. It is hovered, focused and selected as a whole, and indented by its depth.
ChevronButtonOpens and closes an item that has children. Items without children get an empty space, so labels line up.
CheckboxCheckboxWith multiple selection: one before each item.
IconsvgBefore the label. It can change when the item is open.
LabelspanThe title, cut with an ellipsis when it is too long.
BadgespanA 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.

KeyWhat it does
Arrow Down, Arrow UpMove to the next or previous row
Arrow RightOpen the item, if it has children and is closed
Arrow LeftClose the item, or move to its parent when it is closed
SpaceSelect or deselect the item (with a selectionMode)
EnterRun the item's action or follow its link
Type a letterJump to the next item whose title starts with it

Examples

Click a chevron to open a folder, or use the arrow keys.

Usage

src
app
layout.tsx
page.tsx
globals.css

Icons

icon goes before the label. expandedIcon replaces it while the item is open, for an open folder.

Open folder
notes.md

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.

src
app
layout.tsx
page.tsx
globals.css
package.json
README.md

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.

src
components
button.tsx
select.tsx
package.json
README.md

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.

src
package.json
README.md

open: src

Disabled items

disabledKeys, or isDisabled on an item, makes it unavailable: it cannot be selected or acted on.

src
components

Badges

A short value at the end of the row, such as a count.

Home
Docs
Notifications3
Settings
Theme
Pluginsnew

Sizes

size=sm
app.tsx
lib.ts
size=md
app.tsx
lib.ts
size=lg
app.tsx
lib.ts

Variants

A frame around the tree, or none when it sits inside something that already has one.

plain
app.tsx
outline
app.tsx

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

PropTypeDefault
aria-labelstring- (give it one)
selectionMode"none" | "single" | "multiple""none"
selectedKeysSelection-
defaultSelectedKeysSelection-
onSelectionChange(keys: Selection) => void-
disallowEmptySelectionbooleanfalse
expandedKeysIterable<Key>-
defaultExpandedKeysIterable<Key>-
onExpandedChange(keys: Set<Key>) => void-
disabledKeysIterable<Key>-
onAction(key: Key) => void-
renderEmptyState() => ReactNode"Nothing here."
size"sm" | "md" | "lg""md"
variant"plain" | "outline""plain"
showCheckboxesbooleantrue

TreeItem

PropTypeDefault
idKey- (required)
titleReactNode- (required)
textValuestringthe title, if it is a string
iconReactNode-
expandedIconReactNode-
badgeReactNode-
hrefstring-
onAction() => void-
isDisabledbooleanfalse
childrenTreeItem elements-