tree-view.tsx
Overview
tree-view.tsx is a React component file that implements a highly customizable and accessible Tree View UI component. It enables rendering hierarchical data structures with expandable/collapsible nodes and selectable leaf and node items. The component supports:
Recursive rendering of nested tree nodes and leaves.
Single-item selection with callbacks.
Expand/collapse controls via an accordion-style UI.
Custom icons per node state (default, selected, open).
Optional action elements per tree item.
Styling variants using
class-variance-authority.Keyboard and screen-reader accessibility by leveraging Radix UI’s Accordion primitives.
This file is designed to be used in client-side React applications and is especially suited for file explorers, navigation trees, or any UI requiring hierarchical data display.
Exports
TreeView
The main Tree View component. Accepts tree data and renders the entire hierarchical structure.
TreeDataItem
TypeScript interface defining the shape of each tree item.
Detailed API
Interface: TreeDataItem
Represents a single node or leaf in the tree.
Property | Type | Description |
|---|---|---|
|
| Unique identifier for the tree item. |
|
| Display name of the item shown in the tree. |
|
| Optional default icon for the item. |
|
| Optional icon to display when the item is selected. |
|
| Optional icon to display when the node is expanded/open. |
|
| Optional array of child items, indicating this item is a node. |
| Optional React elements (e.g., buttons) shown when the item is selected. | |
| Optional click handler triggered when the item is selected. |
Component: TreeView
Props
Name | Type | Default | Description |
|---|---|---|---|
|
|
| Required |
|
|
| The |
| [(item: TreeDataItem \ | undefined) => void](/projects/311/73394) |
|
|
|
| If true, expands all nodes by default. |
|
|
| Default icon for tree nodes (items with children). |
|
|
| Default icon for leaf items (items without children). |
|
|
| Optional additional CSS classes for the container div. |
...others | Other native div attributes passed through. |
Usage Example
import { TreeView, TreeDataItem } from './tree-view';
import { FolderIcon, FileIcon } from './icons';
const data: TreeDataItem[] = [
{
id: '1',
name: 'Documents',
children: [
{ id: '2', name: 'Resume.pdf', icon: FileIcon },
{ id: '3', name: 'CoverLetter.docx', icon: FileIcon },
],
icon: FolderIcon,
},
];
export function App() {
const handleSelect = (item?: TreeDataItem) => {
console.log('Selected:', item?.name);
};
return (
<TreeView
data={data}
initialSelectedItemId="2"
onSelectChange={handleSelect}
defaultNodeIcon={FolderIcon}
defaultLeafIcon={FileIcon}
/>
);
}
Internal Components & Functions
TreeItem
Recursive component that renders a list of tree items (
TreeDataItem[]).Differentiates between nodes (with children) and leaves (without children).
Props: extends
TreePropswith:selectedItemId: currently selected item ID.handleSelectChange: callback to update selection.expandedItemIds: array of IDs currently expanded.defaultNodeIcon,defaultLeafIcon: icons to use if item icons are undefined.
TreeNode
Renders a single tree node using Radix UI Accordion primitives.
Manages its expanded state internally with hooks.
Props:
item: The current tree node.handleSelectChange: selection handler.expandedItemIds: expanded nodes IDs.selectedItemId: currently selected ID.defaultNodeIcon,defaultLeafIcon: fallback icons.
On click, the node triggers selection and optionally its
onClick.
TreeLeaf
Renders a leaf node (no children).
Props:
item: leaf item.selectedItemId: current selection.handleSelectChange: selection handler.defaultLeafIcon: fallback icon.
Styled as clickable and supports selection highlighting.
AccordionTrigger & AccordionContent
Wrappers around Radix UI Accordion triggers and content.
Adds custom styling and chevron icon that rotates on expand/collapse.
TreeIcon
Determines which icon to display for a tree item based on its state:
Selected →
selectedIconif present.Open →
openIconif present.Otherwise →
iconor default.
TreeActions
Conditionally renders action elements (e.g., buttons) for a selected item.
Visible on hover and when the item is selected.
Implementation Details & Algorithms
State Management: The selected item ID and expanded nodes are managed in local component state using React hooks.
Expansion Logic: Uses a recursive
walkTreeItemsfunction to determine which nodes to expand based on the initially selected item andexpandAllflag.Radix Accordion Integration: Uses Radix UI's Accordion primitives for accessible expand/collapse behavior.
Styling: Utilizes
cva(class variance authority) to define base and selected styles with hover effects and background highlights.Recursive Rendering: The tree recursively renders nodes and leaves depending on the presence of children.
Interaction With Other Parts of the System
Utility Imports: Imports
cnutility for conditional className joining from@/lib/utils.Icons: Uses
ChevronRightfromlucide-reactfor expand/collapse indicators.Radix UI Accordion: Relies on
@radix-ui/react-accordionfor accessible accordion behavior.Styling: Uses the
class-variance-authoritypackage for conditional styling.
This component is designed to be a standalone UI element but can be integrated into larger applications wherever hierarchical data visualization is needed.
Mermaid Diagram: Component Structure
componentDiagram
direction TB
component TreeView {
+data: TreeDataItem[] | TreeDataItem
+initialSelectedItemId?: string
+onSelectChange?: (item) => void
+expandAll?: boolean
+defaultNodeIcon?: any
+defaultLeafIcon?: any
}
component TreeItem {
+data: TreeDataItem[] | TreeDataItem
+selectedItemId?: string
+handleSelectChange(item)
+expandedItemIds: string[]
+defaultNodeIcon?: any
+defaultLeafIcon?: any
}
component TreeNode {
+item: TreeDataItem
+handleSelectChange(item)
+expandedItemIds: string[]
+selectedItemId?: string
+defaultNodeIcon?: any
+defaultLeafIcon?: any
}
component TreeLeaf {
+item: TreeDataItem
+selectedItemId?: string
+handleSelectChange(item)
+defaultLeafIcon?: any
}
component AccordionTrigger
component AccordionContent
component TreeIcon
component TreeActions
TreeView --> TreeItem : renders
TreeItem --> TreeNode : if has children
TreeItem --> TreeLeaf : if no children
TreeNode --> AccordionTrigger : uses
TreeNode --> AccordionContent : uses
TreeNode --> TreeItem : recursive render of children
TreeNode --> TreeIcon : renders icon
TreeLeaf --> TreeIcon : renders icon
TreeNode --> TreeActions : renders actions
TreeLeaf --> TreeActions : renders actions
Summary
The tree-view.tsx file provides a robust, accessible, and flexible React Tree View component with support for nested data, selection, expansion, custom icons, and item actions. It encapsulates complex UI behaviors using Radix UI primitives and React hooks, while maintaining clean styling and extensibility.
This component is ideal for applications requiring an interactive hierarchical data display with rich customization and accessible interactions.