78Build a nested file explorer with add, rename, and delete
Problem
Build a VS Code–style file explorer. A tree node is { id, name, type: "folder" | "file", children? } (folders have children).
First write pure, immutable helpers:
insertNode(tree, parentId, node): addnodeto the folderparentId.renameNode(tree, id, name): rename a node.removeNode(tree, id): remove a node and everything inside it.sortChildren(children): folders first, then files, each alphabetical (case-insensitive, with numbers in natural order:file2beforefile10).
insertNode and renameNode throw an Error when the name is empty or already used by a sibling (case-insensitive).
Then build <FileExplorer initialTree={root} />, where root is a folder:
- render
<ul role="tree">with<li role="treeitem">per node; folders havearia-expandedand start collapsed (the root's direct children are visible); - clicking a folder's name toggles it;
- each node has buttons labelled
Rename {name}andDelete {name}; folders also haveNew file in {name}, which adds anuntitledfile (oruntitled 2,untitled 3…) and opens the folder; Renameswaps the name for an<input aria-label="New name for {name}">;Entersaves,Escapecancels, and an invalid name shows arole="alert"message.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
Video walkthrough
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
All three edits are "find a node and replace it". Write updateNode(tree, id, fn): if tree.id === id, return fn(tree); if it is a folder, map its children recursively. Only the path to the edited node is copied; every other branch keeps its reference, which keeps React re-renders cheap.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.