Skip to main content

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: null leaf 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.