How to Build a React Tree Select Component
Learn to build a React tree select component with recursive rendering, expandable branches, multi-select checkboxes, state management, and styling.

Image used for representation purposes only.
A React tree select component lets users choose items arranged in a hierarchy, such as folders, product categories, or organizational units. This tutorial builds a lightweight, multi-select tree from nested data. Users can expand and collapse branches and select individual nodes. The example keeps parent and child selections independent; selecting a parent does not automatically select its descendants.
What you’ll build
The component will:
- Render nested data recursively.
- Track expanded nodes and selected nodes separately.
- Let users select multiple items with checkboxes.
- Notify a parent component whenever the selection changes.
The code uses React’s useState Hook for UI state. Each piece of state has one owner—the TreeSelect component—and child nodes receive values and event handlers through props. This follows React’s guidance to keep a single source of truth for each piece of state and lift shared state to the appropriate parent. (react.dev
)
1. Define the tree data
Represent each node with a stable id, a display label, and an optional children array. A node with no children is treated as a leaf.
const treeData = [
{
id: 'engineering',
label: 'Engineering',
children: [
{ id: 'frontend', label: 'Frontend' },
{
id: 'backend',
label: 'Backend',
children: [
{ id: 'apis', label: 'APIs' },
{ id: 'infrastructure', label: 'Infrastructure' },
],
},
],
},
{
id: 'design',
label: 'Design',
children: [
{ id: 'product-design', label: 'Product design' },
{ id: 'research', label: 'Research' },
],
},
];
IDs should be unique and stable. React uses keys to track list items when rendering, inserting, deleting, or reordering elements, so the node ID is a better key than an array index. (react.dev )
2. Build a recursive node component
A tree is naturally recursive: each node renders itself and, when expanded, renders its children using the same component. The example below uses ordinary nested lists, buttons, and checkboxes. The expand button has an accessible label and aria-expanded, while the checkbox’s label comes from the node name.
function TreeNode({
node,
selectedIds,
expandedIds,
onToggleSelected,
onToggleExpanded,
}) {
const hasChildren = Boolean(node.children?.length);
const isExpanded = expandedIds.has(node.id);
const isSelected = selectedIds.has(node.id);
return (
<li>
<div className="tree-row">
{hasChildren ? (
<button
type="button"
className="tree-toggle"
aria-label={`${isExpanded ? 'Collapse' : 'Expand'} ${node.label}`}
aria-expanded={isExpanded}
onClick={() => onToggleExpanded(node.id)}
>
{isExpanded ? '▾' : '▸'}
</button>
) : (
<span className="tree-spacer" aria-hidden="true" />
)}
<label>
<input
type="checkbox"
checked={isSelected}
onChange={() => onToggleSelected(node.id)}
/>
{node.label}
</label>
</div>
{hasChildren && isExpanded && (
<ul>
{node.children.map((child) => (
<TreeNode
key={child.id}
node={child}
selectedIds={selectedIds}
expandedIds={expandedIds}
onToggleSelected={onToggleSelected}
onToggleExpanded={onToggleExpanded}
/>
))}
</ul>
)}
</li>
);
}
The key belongs on the element returned directly from map()—here, the child TreeNode. The component uses a native checkbox so users can interact with selections using standard browser and keyboard behavior.
3. Add the tree state and selection logic
Store selections and expansion state in separate Set objects. A Set makes membership checks straightforward, and creating a new Set for every update avoids mutating existing React state.
import { useState } from 'react';
export default function TreeSelect({ data, onChange }) {
const [selectedIds, setSelectedIds] = useState(() => new Set());
const [expandedIds, setExpandedIds] = useState(() => new Set());
function toggleSelected(id) {
const next = new Set(selectedIds);
if (next.has(id)) {
next.delete(id);
} else {
next.add(id);
}
setSelectedIds(next);
onChange?.([...next]);
}
function toggleExpanded(id) {
const next = new Set(expandedIds);
if (next.has(id)) {
next.delete(id);
} else {
next.add(id);
}
setExpandedIds(next);
}
function clearSelection() {
setSelectedIds(new Set());
onChange?.([]);
}
return (
<div className="tree-select">
<button type="button" onClick={clearSelection}>
Clear selection
</button>
<ul>
{data.map((node) => (
<TreeNode
key={node.id}
node={node}
selectedIds={selectedIds}
expandedIds={expandedIds}
onToggleSelected={toggleSelected}
onToggleExpanded={toggleExpanded}
/>
))}
</ul>
<p aria-live="polite">
{selectedIds.size} item{selectedIds.size === 1 ? '' : 's'} selected
</p>
</div>
);
}
onChange is optional. When provided, it receives an array of selected IDs after a selection change or when the user clears the selection. This makes the component easy to connect to a form or another component without requiring the parent to manage its state.
4. Use the component
Pass the nested data and an onChange handler from your application:
function App() {
function handleSelectionChange(ids) {
console.log('Selected node IDs:', ids);
}
return (
<main>
<h1>Choose teams</h1>
<TreeSelect data={treeData} onChange={handleSelectionChange} />
</main>
);
}
For example, selecting “Frontend” and “Research” produces ['frontend', 'research']. The order of IDs reflects the order in which they were selected. If your application needs a particular ordering, sort the IDs before calling onChange.
5. Add basic styling
.tree-select ul {
list-style: none;
margin: 0;
padding-left: 1.25rem;
}
.tree-select > ul {
padding-left: 0;
}
.tree-row {
align-items: center;
display: flex;
gap: 0.35rem;
min-height: 2rem;
}
.tree-row label {
align-items: center;
cursor: pointer;
display: inline-flex;
gap: 0.4rem;
}
.tree-toggle {
background: transparent;
border: 0;
cursor: pointer;
font-size: 1rem;
min-width: 1.5rem;
}
.tree-spacer {
display: inline-block;
min-width: 1.5rem;
}
Common enhancements
Cascade selection to descendants
Some interfaces expect selecting a parent to select every descendant. That behavior requires a helper that collects a node’s descendant IDs, then adds or removes them from the selected set together. You may also want to derive an indeterminate checkbox state for a parent when only some descendants are selected. Define the desired rules first: should selecting a parent affect all children, and should manually selecting every child automatically select the parent?
Make the component controlled
For form libraries or shared application state, accept selectedIds and onChange as props instead of keeping selection in local state. React describes components whose important values are driven by props as controlled components; this pattern makes the parent responsible for the selection value. (react.dev
)
Add search and large-tree support
A search field can filter nodes while retaining the ancestors needed to show a matching descendant. For very large trees, consider lazy-loading children, limiting how many branches are rendered at once, or using a library designed for virtualization and advanced keyboard navigation.
Testing checklist
Before using the component in production, verify that:
- Expanding and collapsing a branch does not change selection.
- Selecting a node does not unexpectedly select its parent or siblings.
- Clearing selection calls
onChangewith an empty array. - Node IDs are unique and remain stable as data changes.
- Keyboard users can reach and operate every button and checkbox.
- Any cascade-selection and indeterminate-state rules match the product requirements.
This implementation provides a practical foundation for a multi-select tree. Its recursive rendering keeps nested data simple, while separate state for expansion and selection makes the component easier to extend with controlled values, search, or cascading selection.
Related Posts

Building an Accessible React Range Slider (Single and Two‑Thumb)
Build an accessible React range slider with ARIA, keyboard support, screen reader clarity, and a two‑thumb range implementation with robust form integration.

React Accessibility: Practical ARIA Best Practices
A practical React guide to ARIA—when to use it, when not to, plus patterns for focus, labels, widgets, and testing.

How to Build an Accessible React Banner Notification Component
Learn to build an accessible, reusable React banner notification with clear state management, ARIA semantics, styling, and testing guidance.