Skip to the page

Trees, comments and drag and drop · mid

File explorer tree (recursion)

A file explorer renders a tree with a recursive component, keeps the data (folders and files) separate from UI state (expanded ids as a Set, the selected id), changes the tree with pure, immutable add, rename and delete functions, and follows the ARIA tree pattern for the keyboard.

The notes

What you must know

  • Data: nested { id, name, type: 'folder' | 'file', children? } or normalised { byId, rootIds } with childIds; normalised makes updates O(1) but rendering needs lookups — say which you chose.
  • UI state: expanded = Set of folder ids, selectedId, renamingId; never store 'isOpen' inside the data from the API.
  • Recursive <TreeNode node depth> renders itself for children; indentation by depth.
  • Pure operations: insert (into the right folder, folders first then names sorted with localeCompare numeric), rename (reject an empty name or a duplicate name in the same folder), delete (removes the subtree). Return new objects along the changed path only.
  • Accessibility (tree pattern): role='tree', treeitem with aria-expanded on folders, aria-level, group for children; Up/Down move, Right opens/enters, Left closes/goes to parent; roving tabindex.
  • Nested checkboxes variant: a folder is checked if all leaves are, unchecked if none, indeterminate otherwise; checking a folder checks all its leaves.
  • Extras: lazy-load folder contents on expand, drag to move, search that expands matching paths.

The red pen

Common traps: mistake → fix

  • Mistake: Mutate the nested node then setState(tree)

    Fix: React doesn't see the change.

  • Mistake: Store expanded flags inside data nodes

    Fix: refetching the tree resets UI state.

  • Mistake: Allow duplicate names in one folder

    Fix: confusing and usually against the requirements.

  • Mistake: Deleting a folder leaves its children in a normalised map

    Fix: orphaned entries.

Easy to hard

Questions interviewers ask, easy to hard

  1. Build a VS Code-like file explorer with expand and collapse.
  2. Add create, rename and delete.
  3. Make it keyboard accessible.
  4. Add tri-state checkboxes for folders.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview