How to Display a Folder-like Hierarchy as a Tree in React
To show a folder-like hierarchy as a tree, prepare data where each node can have an array of children, and call the same render function on those child arrays. Keep the open folders in one Set for the whole tree, not as state in each folder. This way, when you close an outer folder and open it again, the open or closed state of the inner folders is still there.
I built a TreeView component without using a library, and checked clicking and arrow-key navigation.
The test environment was Ubuntu 24.04, Node.js 22.22.0, and Chromium 153. I used react / react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I type-checked the .tsx files with tsc, transpiled them with esbuild, and operated Chromium with Playwright. I did not test screen reader speech, touch operation, Firefox, or Safari. I checked the roles and names that screen readers use by reading the accessibility tree Chromium holds, through CDP (Chrome DevTools Protocol).

The cursor, click ripples, and the operation counter in the GIF were added for the recording. The parts that changed on click (the "selected item" text, which is in Japanese in the image, and the components row that stayed open) are highlighted in pink only at that moment.
- 1. Build the hierarchy as nested data with child arrays
- 2. The whole TreeView
- 3. Keep the open folders in one Set for the whole tree
- 4. Handle clicks on a one-row div, not on the li
- 5. Use role="tree" and aria attributes to announce a tree
- 6. Move between visible items with the arrow keys
- 7. When Tab comes back, focus the selected item
Build the hierarchy as nested data with child arrays
Each item in the data passed to the tree is represented by a TreeNode type. A node with children is a folder, and a node without it is a file. id is a string that identifies each item. It is used as the React key and to record which folders are open.
If you have a list of files as paths like src/App.tsx, you can use buildTree, which splits each path on / and builds nested data. The id of each item is the path from the top to that item. Even if folders with the same name are in different places, their ids do not collide.
import type { TreeNode } from './TreeView';
// Builds nested TreeNodes from a list of paths like "src/App.tsx"
export function buildTree(paths: string[]): TreeNode[] {
const root: TreeNode[] = [];
for (const path of paths) {
let level = root;
const parts = path.split('/');
parts.forEach((name, i) => {
const id = parts.slice(0, i + 1).join('/');
let node = level.find((n) => n.id === id);
if (!node) {
node = i < parts.length - 1 ? { id, name, children: [] } : { id, name };
level.push(node);
}
if (node.children) level = node.children;
});
}
sortTree(root);
return root;
}
// Puts folders first, then sorts items of the same kind by name
function sortTree(nodes: TreeNode[]) {
nodes.sort((a, b) => Number(!a.children) - Number(!b.children) || a.name.localeCompare(b.name, 'ja'));
for (const n of nodes) if (n.children) sortTree(n.children);
}
Folders and files mixed together are hard to scan, so sortTree puts folders first and sorts items of the same kind by name. Here is an example that passes four paths:
buildTree(['src/components/Header.tsx', 'src/App.tsx', 'package.json', 'public/favicon.svg']);
If you write the result as an indented tree, with / after each folder name, it looks like this:
public/
favicon.svg
src/
components/
Header.tsx
App.tsx
package.json
package.json was passed before public/favicon.svg, but it appears after the folders public and src.
The id of each item is the path from the top. For example, the id of Header.tsx is src/components/Header.tsx.
The whole TreeView
This is the code for the TreeView component that displays the tree. You pass the result of buildTree as nodes and the tree's name as label. When an item is selected, onSelect is called.
import { useRef, useState, type FocusEvent, type KeyboardEvent } from 'react';
export type TreeNode = {
id: string;
name: string;
children?: TreeNode[]; // If present, this is a folder
};
type Props = {
nodes: TreeNode[];
label: string;
onSelect?: (node: TreeNode) => void;
};
type Visible = { node: TreeNode; parentId: string | null };
// Walks only the open folders and lists items in the order they appear on screen
function listVisible(nodes: TreeNode[], expanded: Set<string>, parentId: string | null = null): Visible[] {
return nodes.flatMap((node) => [
{ node, parentId },
...(node.children && expanded.has(node.id) ? listVisible(node.children, expanded, node.id) : []),
]);
}
export function TreeView({ nodes, label, onSelect }: Props) {
const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
const [selectedId, setSelectedId] = useState<string | null>(null);
// The item where Tab stops (the first item at the start)
const [focusedId, setFocusedId] = useState<string | null>(nodes[0]?.id ?? null);
const itemRefs = useRef(new Map<string, HTMLLIElement>());
const toggle = (id: string, open?: boolean) => {
setExpanded((prev) => {
const next = new Set(prev);
if (open ?? !next.has(id)) next.add(id);
else next.delete(id);
return next;
});
};
const moveFocus = (id: string) => {
setFocusedId(id);
itemRefs.current.get(id)?.focus();
};
const select = (node: TreeNode) => {
setSelectedId(node.id);
onSelect?.(node);
};
const handleKeyDown = (e: KeyboardEvent<HTMLUListElement>) => {
const visible = listVisible(nodes, expanded);
const index = visible.findIndex((v) => v.node.id === focusedId);
if (index < 0) return;
const { node, parentId } = visible[index];
const isOpen = expanded.has(node.id);
switch (e.key) {
case 'ArrowDown':
if (index < visible.length - 1) moveFocus(visible[index + 1].node.id);
break;
case 'ArrowUp':
if (index > 0) moveFocus(visible[index - 1].node.id);
break;
case 'ArrowRight':
if (node.children && !isOpen) toggle(node.id, true);
else if (node.children?.length) moveFocus(node.children[0].id);
break;
case 'ArrowLeft':
if (node.children && isOpen) toggle(node.id, false);
else if (parentId) moveFocus(parentId);
break;
case 'Home':
moveFocus(visible[0].node.id);
break;
case 'End':
moveFocus(visible[visible.length - 1].node.id);
break;
case 'Enter':
select(node);
if (node.children) toggle(node.id);
break;
default:
return; // Other keys keep their default browser behavior
}
e.preventDefault();
};
// When focus leaves the tree, the next Tab into it returns to the selected item
const handleBlur = (e: FocusEvent<HTMLUListElement>) => {
if (e.currentTarget.contains(e.relatedTarget)) return; // Focus only moved within the tree
const visible = listVisible(nodes, expanded);
if (visible.some((v) => v.node.id === selectedId)) setFocusedId(selectedId);
};
const renderNodes = (list: TreeNode[], level: number) =>
list.map((node) => {
const isFolder = node.children !== undefined;
const isOpen = expanded.has(node.id);
return (
<li
key={node.id}
role="treeitem"
aria-expanded={isFolder ? isOpen : undefined}
aria-selected={selectedId === node.id}
tabIndex={focusedId === node.id ? 0 : -1}
ref={(el) => {
if (el) itemRefs.current.set(node.id, el);
return () => {
itemRefs.current.delete(node.id);
};
}}
>
{/* An li includes the folder's contents, so the click is handled by a div for one row */}
<div
className="tree-row"
style={{ paddingLeft: level * 20 }}
onClick={() => {
moveFocus(node.id);
select(node);
if (isFolder) toggle(node.id);
}}
>
<span className={isFolder ? (isOpen ? 'chevron open' : 'chevron') : 'chevron none'} aria-hidden="true">
▶
</span>
<span className={isFolder ? 'icon folder' : 'icon file'} aria-hidden="true" />
<span>{node.name}</span>
</div>
{isFolder && isOpen && <ul role="group">{renderNodes(node.children!, level + 1)}</ul>}
</li>
);
});
return (
<ul role="tree" aria-label={label} className="tree" onKeyDown={handleKeyDown} onBlur={handleBlur}>
{renderNodes(nodes, 0)}
</ul>
);
}
On the calling side, pass the data built by buildTree and show the id of the selected item. I left out the last line, which switches between the comparison version and calls createRoot(...).render(...).
import { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { TreeView } from './TreeView';
import { buildTree } from './buildTree';
const paths = [
'src/components/Header.tsx',
'src/components/TreeView.tsx',
'src/App.tsx',
'src/main.tsx',
'public/favicon.svg',
'package.json',
'README.md',
];
const tree = buildTree(paths);
function App() {
const [selected, setSelected] = useState('');
return (
<>
<TreeView nodes={tree} label="プロジェクトのファイル" onSelect={(node) => setSelected(node.id)} />
<p id="selected">選んだ項目:{selected || 'なし'}</p>
</>
);
}
renderNodes handles drawing the tree. It creates an li for each item. If a folder is open, it puts a <ul role="group"> inside and calls renderNodes again on the child array. The depth is counted with the level argument, and the left padding (paddingLeft) increases by 20px per level.
Children are rendered only when their folder is open. When I checked in the test environment, only the top four items were in the DOM at first. Opening src raised the count to seven, and opening components inside it raised it to nine. Contents of closed folders are not created, so even a tree with many items only renders what is visible at first.
Keep the open folders in one Set for the whole tree
The open folders are stored in the expanded state of TreeView, as a Set of folder ids. In toggle, I do not modify the existing Set. Instead, I make a copy with new Set(prev) and then add or remove items. As described in React's useState reference, state objects should be replaced with new ones, not changed in place.
You could also keep the open/closed state inside a component for each folder. For comparison, I also made a version like this:
// Comparison version: the open/closed state is kept in a component for each folder
function Item({ node, level }: { node: TreeNode; level: number }) {
const [open, setOpen] = useState(false);
return (
<li role="treeitem" aria-expanded={node.children ? open : undefined} aria-selected={false}>
<div className="tree-row" style={{ paddingLeft: level * 20 }} onClick={() => setOpen(!open)}>
{node.name}
</div>
{node.children && open && (
<ul role="group">
{node.children.map((child) => (
<Item key={child.id} node={child} level={level + 1} />
))}
</ul>
)}
</li>
);
}
In this version, I opened src and components, closed src, and opened it again. components went back to closed. When I did the same operation with TreeView, components stayed open (the fourth click in the GIF above).
| Operation | Version with state per folder | TreeView |
|---|---|---|
Open src and components |
src and components are open |
src and components are open |
Close src, then open it again |
Only src is open |
src and components are open |
In the version with state per folder, closing src stops rendering the Items inside it. As explained in React's official documentation on preserving and resetting state, the state of a component that is no longer rendered is discarded. The open state of components is lost at that point. In TreeView, expanded is kept as state for the whole tree, so even while the contents are not rendered, the record of which folders were open remains.
If you add an "expand all / collapse all" button, or a process that opens the folder of the selected file, you only need to rebuild the Set if expanded is kept in one place. (I did not build these in this article.)
Handle clicks on a one-row div, not on the li
When a folder is open, its li wraps the ul inside it. When I measured the size with src open, the row for src (.tree-row) was 32px high, but its li was 128px high.
src の li: y=48 高さ=128
src の行(.tree-row): y=48 高さ=32
As explained in React's official documentation on event propagation, a click on a child element also reaches the handlers of its parent elements. So if you handle clicks on the li, clicking a child item would also run the processing for the parent folder. In TreeView, onClick is attached to a div that covers one row. When I clicked the middle of the open src
li, I landed on the row for the child App.tsx, and src/App.tsx was selected. The parent src stayed open.
For the same reason, the visual outline and color are applied to .tree-row, not to the li. These are the background of the selected item and the outline shown when the item is focused with the keyboard. I also turned off the browser's default focus outline on the li. If I had not, the outline would be drawn at the size of the li (128px above), so an open folder would be outlined along with its contents.
.tree li:focus {
outline: none;
}
/* The li wraps the folder's contents, so the outline and color go on the one-row .tree-row */
[role="treeitem"][aria-selected="true"] > .tree-row {
background: #d4f3fa;
}
[role="treeitem"]:focus-visible > .tree-row {
outline: 2px solid #067a98;
outline-offset: -2px;
}
Use role="tree" and aria attributes to announce a tree
Even if the layout looks like a tree, a plain ul and li are treated as a nested list. Following the tree view pattern in the ARIA Authoring Practices Guide (APG) from W3C, I set these attributes:
role="tree"and anaria-labelwith the tree's name on the outermostulrole="treeitem"on each item'slirole="group"on theulthat wraps a folder's contentsaria-expandedonly on folders (truewhen open,falsewhen closed)aria-selectedon items that can be selected
The APG pattern says that items with no children, such as files, should not have aria-expanded. Adding it would make them announced as items with children. In TreeView, I pass a value only when isFolder is true, and set it to undefined for files so the attribute is not output.
This is the output of Playwright's ariaSnapshot() after opening src and components and selecting components.
- tree "プロジェクトのファイル":
- treeitem "public"
- treeitem "src" [expanded]:
- text: src
- group:
- treeitem "components" [expanded] [selected]:
- text: components
- group:
- treeitem "Header.tsx"
- treeitem "TreeView.tsx"
- treeitem "App.tsx"
- treeitem "main.tsx"
- treeitem "package.json"
- treeitem "README.md"
Folders show [expanded], the selected components shows [selected], and the child items are inside the group.
In the same state, I also read Chromium's own accessibility tree with CDP's Accessibility.getFullAXTree. Below are only the tree, treeitem, and group parts (I removed the Chromium: prefix from each line).
tree "プロジェクトのファイル"
treeitem "public" level=1 expanded=false selected=false
treeitem "src" level=1 expanded=true selected=false
treeitem "package.json" level=1 selected=false
treeitem "README.md" level=1 selected=false
group ""
treeitem "components" level=2 expanded=true selected=true
treeitem "App.tsx" level=2 selected=false
treeitem "main.tsx" level=2 selected=false
group ""
treeitem "Header.tsx" level=3 selected=false
treeitem "TreeView.tsx" level=3 selected=false
The li contains the text of its child items, but the name of src was just "src" and did not include the names of its children. Even without aria-level, the depth (level) was counted as 1 to 3 from the nesting of the groups.
Move between visible items with the arrow keys
Keyboard operation also mostly follows the APG pattern (the differences are described in a later section). Only one place in the tree stops Tab, and the arrow keys move between items. This is the roving tabindex approach in the APG's keyboard interface guide. tabIndex is 0 only for the item where Tab stops (focusedId), and -1 for the rest. When I counted after each operation during testing, there was always exactly one item with tabindex="0".
The up and down arrow keys move through the items that are currently visible on screen, in their displayed order. listVisible walks only the open folders and lists the items, and movement goes to the previous or next item in that list. To move focus, I call focus() on the li stored in itemRefs. Since there is one li per item, I followed React's official guide on managing a list of refs with a ref callback and stored them in a Map keyed by id.
This is the result of pressing keys from the top, starting with nothing open, in the test environment:
| Key pressed | Focused item | Open folders | Selected item |
|---|---|---|---|
| Tab | public | None | None |
| ↓ | src | None | None |
| → | src | src | None |
| → | components | src | None |
| → | components | src, components | None |
| ↓ | Header.tsx | src, components | None |
| ← | components | src, components | None |
| ← | components | src | None |
| ← | src | src | None |
| End | README.md | src | None |
| Home | public | src | None |
| Enter | public | public, src | public |
| ↓ | favicon.svg | public, src | public |
| ↑ | public | public, src | public |
| ↑ (at the top, pressed again) | public | public, src | public |
On a closed folder, the right arrow key only opens it, and focus does not move. On an open folder, pressing it moves focus to the first child. The left arrow key does the opposite: on an open folder it closes the folder, and on a file or a closed folder it moves focus to the parent folder. The End key skipped the closed public folder's contents and moved to README.md, the last visible item.
Moving with the arrow keys does not select an item. Selection is done with the Enter key or a click. The APG pattern treats focus and selection as separate, and it asks that they be shown differently. In TreeView, the selected item is shown with a background color, and the focused item with an outline. In the test environment, the outline appeared on the favicon.svg row after moving there with the arrow keys, and the selected public row showed only the background color. The outline is applied with :focus-visible, so in the test Chromium it did not appear on the README.md row I clicked.
The APG pattern also describes type-ahead (jumping to an item by typing the first letters of its name) and selecting multiple items. TreeView does not implement these, and I did not test them. The APG pattern also says that for trees that load items as focus moves or while scrolling, and that do not have all items in the DOM, you should add aria-level, aria-setsize, and aria-posinset. The approach in this article applies only when all the data is held locally.
When Tab comes back, focus the selected item
The APG pattern says that when focus enters a tree where one item can be selected, focus should go to the selected item if there is one, and otherwise to the first item. TreeView follows this in handleBlur. When focus leaves the tree (when relatedTarget is not inside the tree), if the selected item is visible, focusedId is set back to that item.
I tested this by placing a button after the tree. I selected public, moved focus to favicon.svg, and pressed Tab, which moved focus to the button. Then I pressed Shift+Tab, and focus returned to the selected public.
When nothing is selected, focus returns to the item that had focus last, not the first item. I moved with the arrow keys to package.json, left the tree with Tab, and came back with Shift+Tab. Focus returned to package.json. This behavior differs from the APG pattern and is my own decision. When the selected item is inside a closed folder, the behavior is also to return to the last item that had focus (I did not test this case). When entering the tree for the first time, focusedId starts at the first item, so focus goes to the first item, as in the APG pattern.
Inside the tree, focusedId follows the arrow keys. When focus leaves the tree, it is set back to the selected item. Only one item has tabIndex set to 0, so no matter how many items the tree has, a single Tab press moves past the whole tree.





