---
title: "Tree View · UI SDK — StyleX Blocks"
description: "Nested hierarchies with expandable branches, indent guides, and depth-aware padding."
url: "https://stylexblocks.com/components/ui-sdk/tree-view/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Tree View

Nested hierarchies with expandable branches, indent guides, and depth-aware padding.

- Behavior engine: UI SDK
- Also available for: [Ark UI](https://stylexblocks.com/components/ark-ui/tree-view.md), [Base UI](https://stylexblocks.com/components/base-ui/tree-view.md)
- Category: Display
- Variants: subtle, solid
- Sizes: xs, sm, md
- Used in blocks: [Canvas Editor](https://stylexblocks.com/block/ui-sdk/canvas-editor.md), [File Explorer](https://stylexblocks.com/block/ui-sdk/file-explorer.md), [IDE Workspace](https://stylexblocks.com/block/ui-sdk/ide.md), [Page Editor](https://stylexblocks.com/block/ui-sdk/page-editor.md)
- HTML page: https://stylexblocks.com/components/ui-sdk/tree-view/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add tree-view
```

Equivalent: `npx shadcn add @stylexblocks/tree-view`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/tree-view.json

## Usage

```tsx
import { TreeView } from "#components/ui/ui-sdk/tree-view.tsx";

export function Example() {
  return (
    // variant/size resolve once on Root; arrow keys, typeahead, selection
    // and --tree-level indentation come from UI SDK's tree. Branch is its
    // item, BranchControl the row (its label), BranchContent its group.
    <TreeView.Root defaultExpandedValue={["src"]} size="md">
      <TreeView.Tree aria-label="Files">
        <TreeView.Branch value="src">
          <TreeView.BranchControl>
            <TreeView.BranchIndicator>
              <TreeView.Icon viewBox="0 0 16 16">{/* chevron */}</TreeView.Icon>
            </TreeView.BranchIndicator>
            <TreeView.BranchText>src</TreeView.BranchText>
          </TreeView.BranchControl>
          <TreeView.BranchContent>
            <TreeView.BranchIndentGuide />
            <TreeView.Item value="src/index.ts">
              <TreeView.ItemText>index.ts</TreeView.ItemText>
            </TreeView.Item>
          </TreeView.BranchContent>
        </TreeView.Branch>
      </TreeView.Tree>
    </TreeView.Root>
  );
}
```

## Source

`components/ui/ui-sdk/tree-view.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useContext, useId } from "react";
import { mergeProps, renderElement, type PartProps } from "@ui-sdk/react/primitive";
import {
  Tree as UiSdkTree,
  TreeGroup as UiSdkTreeGroup,
  TreeItem as UiSdkTreeItem,
  TreeItemIndicator as UiSdkTreeItemIndicator,
  TreeItemLabel as UiSdkTreeItemLabel,
  type TreeProps as UiSdkTreeProps,
} from "@ui-sdk/react/tree";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
  defineSlotRecipe,
  fromMap,
  resolveSlotStyles,
  variantDataAttrs,
  type WithStyleOverrides,
} from "#lib/recipe-props.ts";
import { treeViewTreeIconVars } from '@stylexblocks/ui/slot-recipes/tree-view.stylex.ts'

import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'


const treeViewRoot = stylex.create({
  base: {
    width: sizes.full,
    display: 'flex',
    flexDirection: 'column',
    gap: spacing._2,
  },
})

const treeViewTree = stylex.create({
  base: {
    display: 'flex',
    flexDirection: 'column',
    '--tree-item-gap': spacing._2,
    '--tree-indentation':
      'calc(var(--tree-indent-size) + var(--tree-icon-size) * 0.5)',
    [treeViewTreeIconVars.width]: 'var(--tree-icon-size)',
    [treeViewTreeIconVars.height]: 'var(--tree-icon-size)',
  },
})

const treeViewTreeSizes = stylex.create({
  md: {
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    '--tree-indent-size': spacing._4,
    '--tree-icon-size': spacing._4,
    '--tree-padding-inline': spacing._3,
    '--tree-padding-block': spacing._1_5,
  },
  sm: {
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
    '--tree-indent-size': spacing._4,
    '--tree-icon-size': spacing._3,
    '--tree-padding-inline': spacing._3,
    '--tree-padding-block': spacing._1,
  },
  xs: {
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
    '--tree-indent-size': spacing._4,
    '--tree-icon-size': spacing._3,
    '--tree-padding-inline': spacing._2,
    '--tree-padding-block': spacing._1,
  },
})

const treeViewTreeIcon = stylex.create({
  base: {
    width: treeViewTreeIconVars.width,
    height: treeViewTreeIconVars.height,
  },
})

const treeViewLabel = stylex.create({
  base: {
    fontWeight: fontWeights.medium,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
})

const treeViewBranch = stylex.create({
  base: {
    position: 'relative',
  },
})

const treeViewBranchContent = stylex.create({
  base: {
    position: 'relative',
  },
})

const treeViewBranchContentAnimateContents = stylex.create({
  true: {
    overflow: 'hidden',
    animationName: {
      default: null,
      ':is([data-open], [data-state="open"])': 'expand-height, fade-in',
      ':is([data-closed], [data-state="closed"])': 'collapse-height, fade-out',
    },
    animationDuration: {
      default: null,
      ':is([data-open], [data-state="open"])': durations.moderate,
      ':is([data-closed], [data-state="closed"])': durations.moderate,
    },
  },
})

const treeViewBranchIndentGuide = stylex.create({
  base: {
    height: '100%',
    width: '1px',
    backgroundColor: semanticColors.border,
    position: 'absolute',
    '--tree-depth': 'calc(var(--depth) - 1)',
    '--tree-indentation-offset':
      'calc(var(--tree-indentation) * var(--tree-depth))',
    '--tree-offset':
      'calc(var(--tree-padding-inline) + var(--tree-indentation-offset))',
    insetInlineStart: 'calc(var(--tree-offset) + var(--tree-icon-size) * 0.5)',
    zIndex: 1,
  },
})

const treeViewBranchIndicator = stylex.create({
  base: {
    color: semanticColors.fgMuted,
    transformOrigin: 'center',
    transitionDuration: durations.moderate,
    transitionProperty: 'transform',
    transitionTimingFunction: 'ease-in-out',
  },
})

const treeViewBranchTrigger = stylex.create({
  base: {
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
  },
})

const treeViewBranchControl = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    gap: 'var(--tree-item-gap)',
    borderRadius: semanticRadii.controlMd,
    userSelect: 'none',
    position: 'relative',
    '--tree-depth': 'calc(var(--depth) - 1)',
    '--tree-indentation-offset':
      'calc(var(--tree-indentation) * var(--tree-depth))',
    '--tree-offset':
      'calc(var(--tree-padding-inline) + var(--tree-indentation-offset))',
    paddingInlineStart: 'var(--tree-offset)',
    paddingInlineEnd: 'var(--tree-padding-inline)',
    paddingBlock: 'var(--tree-padding-block)',
    outlineWidth: {
      default: null,
      ':focus-visible': 'var(--focus-ring-width, 0)',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '0px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
    '--focus-ring-color': semanticColors.borderEmphasized,
    '--focus-ring-width': '2px',
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    cursor: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
  },
})

const treeViewBranchControlVariants = stylex.create({
  subtle: {},
  solid: {},
})

const treeViewItem = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    gap: 'var(--tree-item-gap)',
    borderRadius: semanticRadii.controlMd,
    userSelect: 'none',
    position: 'relative',
    '--tree-depth': 'calc(var(--depth) - 1)',
    '--tree-indentation-offset':
      'calc(var(--tree-indentation) * var(--tree-depth))',
    '--tree-offset':
      'calc(var(--tree-padding-inline) + var(--tree-indentation-offset))',
    paddingInlineStart: 'var(--tree-offset)',
    paddingInlineEnd: 'var(--tree-padding-inline)',
    paddingBlock: 'var(--tree-padding-block)',
    outlineWidth: {
      default: null,
      ':focus-visible': 'var(--focus-ring-width, 0)',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '0px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
    '--focus-ring-color': semanticColors.borderEmphasized,
    '--focus-ring-width': '2px',
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    cursor: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
  },
})

const treeViewItemVariants = stylex.create({
  subtle: {},
  solid: {},
})

const treeViewItemText = stylex.create({
  base: {
    flex: 1,
  },
})

const treeViewBranchText = stylex.create({
  base: {
    flex: 1,
  },
})

const treeViewNodeCheckbox = stylex.create({
  base: {
    display: 'inline-flex',
  },
})

export type TreeViewSize = keyof typeof treeViewTreeSizes

export type TreeViewVariant = keyof typeof treeViewBranchControlVariants

export type TreeViewAnimateContent =
  keyof typeof treeViewBranchContentAnimateContents

// What the generated recipe doesn't carry: interactive row affordances, the
// selected/expanded treatment (palette-aware), and the bridges to UI SDK's
// tree. UI SDK keeps focus on the item (the row's parent), not on the
// label that is the row, so the focus ring keys off the focused parent and
// the item's own outline is dropped. The recipes indent rows via `--depth`;
// UI SDK publishes the item's level as `--tree-level`, which every row,
// group and guide inside the item inherits.
const treeStatic = stylex.create({
  item: {
    outlineStyle: "none",
  },
  row: {
    "--depth": "var(--tree-level)",
    cursor: "pointer",
    color: semanticColors.fg,
    backgroundColor: { default: "transparent", ":hover": semanticColors.bgMuted },
    outlineWidth: {
      default: null,
      ":is(:focus-visible > *)": "var(--focus-ring-width, 0)",
    },
    outlineOffset: {
      default: null,
      ":is(:focus-visible > *)": "0px",
    },
    outlineStyle: {
      default: null,
      ":is(:focus-visible > *)": "solid",
    },
    outlineColor: {
      default: null,
      ":is(:focus-visible > *)": colorPalette.focusRing,
    },
  },
  guide: {
    "--depth": "var(--tree-level)",
  },
  group: {
    // UI SDK's documented panel animation: transition the measured height
    // to and from zero on data-starting-style / data-ending-style. A panel
    // that starts open just appears (the shared keyframes replayed on every
    // page load and before hydration the measured var is unset).
    animationName: "none",
    height: {
      default: "var(--tree-group-height, auto)",
      ":is([data-starting-style], [data-ending-style])": "0px",
    },
    opacity: {
      default: 1,
      ":is([data-starting-style], [data-ending-style])": 0,
    },
    transitionProperty: "height, opacity",
    transitionDuration: {
      default: "200ms",
      "@media (prefers-reduced-motion: reduce)": "0s",
    },
    transitionTimingFunction: "ease",
  },
  indicatorExpanded: {
    transform: {
      default: null,
      ":is([data-expanded])": "rotate(90deg)",
    },
  },
});

const treeRowSelected = stylex.create({
  subtle: {
    backgroundColor: {
      default: null,
      ":is([data-selected])": colorPalette.muted,
    },
    color: {
      default: null,
      ":is([data-selected])": colorPalette.fg,
    },
  },
  solid: {
    backgroundColor: {
      default: null,
      ":is([data-selected])": colorPalette.solid,
    },
    color: {
      default: null,
      ":is([data-selected])": colorPalette.contrast,
    },
  },
});

const treeViewRecipe = defineSlotRecipe({
  slots: {
    root: { styles: treeViewRoot },
    tree: { styles: treeViewTree, sizes: treeViewTreeSizes },
    label: { styles: treeViewLabel },
    branch: { styles: treeViewBranch },
    branchContent: { styles: treeViewBranchContent },
    branchIndentGuide: { styles: treeViewBranchIndentGuide },
    branchIndicator: { styles: treeViewBranchIndicator },
    branchTrigger: { styles: treeViewBranchTrigger },
    branchControl: {
      styles: treeViewBranchControl,
      variants: treeViewBranchControlVariants,
    },
    branchText: { styles: treeViewBranchText },
    item: { styles: treeViewItem, variants: treeViewItemVariants },
    itemText: { styles: treeViewItemText },
    nodeCheckbox: { styles: treeViewNodeCheckbox },
  },
  defaultVariants: { size: "md", variant: "subtle" },
});

const { withProvider, withContext, VariantContext } =
  createSlotRecipeContext(treeViewRecipe);

interface ExpandedOptions {
  expandedValue?: string[];
  defaultExpandedValue?: string[];
  onExpandedChange?: (details: { expandedValue: string[] }) => void;
}

// The Root takes the expanded-state props (same shape as the other
// engines); UI SDK reads them on its Tree part, so they travel there
// through context.
const ExpandedContext = createContext<ExpandedOptions>({});

export type TreeViewRootProps = WithStyleOverrides<PartProps<"div">> &
  ExpandedOptions & {
    variant?: "subtle" | "solid";
    size?: "md" | "sm" | "xs";
  };

function RootNode({
  render,
  expandedValue,
  defaultExpandedValue,
  onExpandedChange,
  ...rest
}: PartProps<"div"> & ExpandedOptions) {
  const v = useContext(VariantContext);
  const element = renderElement(
    "div",
    mergeProps({ ...variantDataAttrs(v) }, rest),
    render,
    v,
  );
  return (
    <ExpandedContext.Provider
      value={{ expandedValue, defaultExpandedValue, onExpandedChange }}
    >
      {element}
    </ExpandedContext.Provider>
  );
}

export type TreeViewTreeProps = Omit<UiSdkTreeProps, "expanded" | "defaultExpanded" | "onExpandedChange">;

function TreeNode(props: TreeViewTreeProps) {
  const { expandedValue, defaultExpandedValue, onExpandedChange } =
    useContext(ExpandedContext);
  return (
    <UiSdkTree
      expanded={expandedValue}
      defaultExpanded={defaultExpandedValue}
      onExpandedChange={
        onExpandedChange
          ? (expanded) => onExpandedChange({ expandedValue: expanded })
          : undefined
      }
      {...props}
    />
  );
}

export type TreeViewBranchProps = React.ComponentProps<typeof UiSdkTreeItem>;

function BranchNode(props: TreeViewBranchProps) {
  return <UiSdkTreeItem {...props} />;
}

export type TreeViewItemProps = Omit<
  React.ComponentProps<typeof UiSdkTreeItemLabel>,
  "value"
> & {
  /** Identifies the item in the tree's selection. Defaults to a generated id. */
  value?: string;
  disabled?: boolean;
};

// UI SDK's item is the focusable treeitem and its label is the row; a leaf
// `TreeView.Item` renders both, with the row styles and props on the label.
function ItemNode({ value, disabled, ...rest }: TreeViewItemProps) {
  const id = useId();
  return (
    <UiSdkTreeItem
      value={value ?? id}
      disabled={disabled}
      {...stylex.props(treeStatic.item)}
    >
      <UiSdkTreeItemLabel {...rest} />
    </UiSdkTreeItem>
  );
}

function IndentGuideNode({ render, ...rest }: PartProps<"span">) {
  return renderElement("span", mergeProps({ "aria-hidden": true }, rest), render);
}

function IconNode({ render, ...rest }: PartProps<"svg">) {
  return renderElement("svg", mergeProps({ "aria-hidden": true }, rest), render);
}

/**
 * TreeView — UI SDK's tree wearing the generated recipe. `<TreeView.Root
 * variant size>` resolves the recipe once and every part inherits it
 * through context; `expandedValue` / `defaultExpandedValue` /
 * `onExpandedChange` control which branches (keyed by `<TreeView.Branch
 * value>`) are open. Arrow-key navigation, typeahead, selection and
 * `--tree-level` indentation are UI SDK's: Branch is its item, BranchControl
 * its label (the row), BranchContent its group. Composition per part via
 * `render`.
 */
export const TreeView = {
  Root: withProvider(RootNode, "root", "TreeViewRoot"),
  Tree: withContext(TreeNode, "tree", "TreeViewTree"),
  Label: withContext("div", "label", "TreeViewLabel"),
  Branch: withContext(
    BranchNode,
    () => [treeViewBranch.base, treeStatic.item],
    "TreeViewBranch",
  ),
  BranchControl: withContext(
    UiSdkTreeItemLabel,
    (v) => [
      ...resolveSlotStyles(treeViewRecipe.slots.branchControl, v),
      treeStatic.row,
      fromMap(treeRowSelected, v.variant),
    ],
    "TreeViewBranchControl",
  ),
  BranchContent: withContext(
    UiSdkTreeGroup,
    () => [
      treeViewBranchContent.base,
      treeViewBranchContentAnimateContents.true,
      treeStatic.group,
    ],
    "TreeViewBranchContent",
  ),
  BranchIndentGuide: withContext(
    IndentGuideNode,
    () => [treeViewBranchIndentGuide.base, treeStatic.guide],
    "TreeViewBranchIndentGuide",
  ),
  BranchIndicator: withContext(
    UiSdkTreeItemIndicator,
    () => [treeViewBranchIndicator.base, treeStatic.indicatorExpanded],
    "TreeViewBranchIndicator",
  ),
  BranchText: withContext("span", "branchText", "TreeViewBranchText"),
  Item: withContext(
    ItemNode,
    (v) => [
      ...resolveSlotStyles(treeViewRecipe.slots.item, v),
      treeStatic.row,
      fromMap(treeRowSelected, v.variant),
    ],
    "TreeViewItem",
  ),
  ItemText: withContext("span", "itemText", "TreeViewItemText"),
  Icon: withContext(IconNode, () => [treeViewTreeIcon.base], "TreeViewIcon"),
};
```
