All questions

Nested Comments

Premium

Nested Comments

Build a threaded comment tree in React. Comments nest arbitrarily deep, so the component has to render itself — a Comment renders its own author and text, then maps over node.children rendering each child as another Comment. On top of that recursion you'll add two edits: posting a reply (append a child under one node) and collapsing a node (hide its subtree).

What you'll build

The starter renders the initial tree in its resting state — every node expanded, no reply box open. Make it interactive:

  1. Hold the tree in state. Lift initialTree into useState. Also track a collapsedIds Set<number> and a replyingId.
  2. Reply. Clicking Reply sets replyingId to that node's id, revealing a <textarea> + Post. Posting appends a new child under that node and clears replyingId.
  3. Edit by id, recursively. Write addReply(tree, id, reply) that walks the tree and rebuilds only the matching branch — new objects, not mutation.
  4. Collapse. The [-] / [+] button toggles the node's id in collapsedIds; a collapsed node hides its .children.

Examples

  • The page shows two root comments; the first has a Linus reply, which has an Ada reply — three levels deep, each indented under a left border.
  • Click Reply on "Grace", type text, click Post — a new child appears indented under Grace, authored by "You".
  • Click [-] on "Linus" — the "Ada: Thanks!" reply underneath disappears; the button flips to [+]. Click again to expand.

Notes

  • One component, called recursively. Comment renders node.children.map((c) => <Comment node={c} />). Give each child a stable key={c.id}.
  • Update immutably. In React, addReply returns a fresh array with only the changed branch rebuilt; mutating node.children in place won't trigger a re-render.
  • A Set for collapsed ids reads cleanly: collapsedIds.has(id) to check, add/delete to toggle. Copy it into a new Set when you update state.
  • Styling (indentation, the left border, the reply box) is already in styles.css; focus on the state and the recursion.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium