FrontendPro

78Build a nested file explorer with add, rename, and delete

mediumAbout 45 minutesCodingreactrecursiontreesimmutability

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): add node to the folder parentId.
  • 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: file2 before file10).

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 have aria-expanded and start collapsed (the root's direct children are visible);
  • clicking a folder's name toggles it;
  • each node has buttons labelled Rename {name} and Delete {name}; folders also have New file in {name}, which adds an untitled file (or untitled 2, untitled 3…) and opens the folder;
  • Rename swaps the name for an <input aria-label="New name for {name}">; Enter saves, Escape cancels, and an invalid name shows a role="alert" message.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Video walkthrough

Stuck? Watch someone solve it, then try again on your own.

GreatFrontEnd React Interview Question - File ExplorerAlpha-Code on YouTubeOpen on YouTube

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.

All 150 answersOne payment, yours forever