117Build a nested drag-and-drop tree editor with optimistic reordering
hardAbout 75 minutesCodingreactdrag-and-droptreesoptimistic-ui
Problem
Build an outline editor (like a docs sidebar) where pages can be dragged into folders and reordered, and every move is saved to a server.
A node is { id, title, children: [] } (every node can have children).
moveNode(tree, nodeId, targetParentId, index)returns a new tree with the node removed from its current place and inserted intotargetParentId's children atindex("root"is the id of the top-level node). Within the same parent,indexrefers to the position after removal. Throw anErrorwhen moving a node into itself or into one of its descendants.<TreeEditor initialTree={root} onMove={async (move) => …} />:- render each node as
<div data-node-id={id} draggable="true">{title}</div>followed by its children in a nested list; - dropping a node on another node's row inserts it before that node (same parent); dropping it on the row's "Drop inside" zone (
<div data-drop-inside={id}>) makes it that node's last child; - apply the move optimistically and call
onMove({ nodeId, parentId, index }); - if
onMoverejects, undo only that move, keep other moves (even ones made after it), and show<p role="alert">.
- render each node as
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Step-by-step
moveNode needs three helpers: find a node (and check whether the target lies inside the moved node's subtree), remove a node returning the tree without it, and insert into a parent at an index. Each is a small recursive function that copies only the path it changes.
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.