Directory Tree
Difficulty: Core
Problem Statementβ
Render nested folder/file tree with expand/collapse on folders.
Live Demoβ
Try the running app below β this is the target behavior for the challenge.
Directory Tree β Live Demo
- File3
What Interviewers Expectβ
- Recursive rendering for nested nodes.
- Local expand state per folder node.
- Handle
children: nullleaf nodes.
Step-by-Step Implementationβ
Step 1 β Recursive TreeNodeβ
If node has children, render toggle + nested list.
if (!node.children) return <li>{node.name}</li>;
Step 2 β Expand stateβ
Keep open boolean in each expandable node.
const [open, setOpen] = useState(false);
Complete Implementationβ
Copy-paste ready single-file solution. Use this as your reference after attempting the challenge yourself, or paste it into CodeSandbox / StackBlitz to run locally.
App.jsx
import React, {useState} from 'react';
const TREE = [
{
name: 'Folder',
children: [
{name: 'File1', children: null},
{name: 'File2', children: null},
],
},
{name: 'File3', children: null},
];
function TreeNode({node}) {
const [open, setOpen] = useState(false);
if (!node.children) {
return <li>{node.name}</li>;
}
return (
<li>
<button type="button" onClick={() => setOpen((value) => !value)}>
{open ? 'βΌ' : 'βΆ'} {node.name}
</button>
{open && (
<ul>
{node.children.map((child) => (
<TreeNode key={child.name} node={child} />
))}
</ul>
)}
</li>
);
}
export default function App() {
return (
<ul>
{TREE.map((node) => (
<TreeNode key={node.name} node={node} />
))}
</ul>
);
}
Final Checklistβ
- UI works for primary flow
- Edge cases handled (empty/disabled/loading where relevant)
- State updates are immutable
- Components are readable and reasonably split
- You can explain trade-offs out loud in an interview
Next Challengeβ
Continue to the next item in the sidebar when you're comfortable implementing this from scratch in 30β45 minutes.