81Build a nested comments component with threaded replies
mediumAbout 40 minutesCodingreactrecursiontrees
Problem
The API returns comments as a flat list: { id, parentId, author, text }, where parentId is null for top-level comments.
- Write
buildTree(comments): return the top-level comments, each with arepliesarray, nested to any depth, preserving the original order. Do it in O(n). - Build
<Comments initialComments={list} currentUser="you" />:- render threads recursively; each comment is an
<article data-comment-id={id}>with the author and text; - a Reply button opens a
<textarea aria-label="Reply to {author}">with a Post reply button; posting adds a reply bycurrentUserunder that comment; - a comment with replies shows a Hide replies (n) button, where
nis the total number of nested replies, which toggles to Show replies (n); - the current user's comments have a Delete button. Deleting a comment with replies keeps the thread and shows
[deleted]instead of the text; deleting one without replies removes it.
- render threads recursively; each comment is an
Try it yourself
Write your solution, run it, then submit to check it against the tests.
App.jsxReact + DOM
Video walkthroughs
Stuck? Watch someone solve it, then try again on your own.
Step-by-step
Create a Map from id to a copy of each comment with an empty replies array. Then walk the list once more: if a comment has a parentId whose node exists, push it into that parent's replies; otherwise it is a root. Two linear passes, no nested loops, and the original order is kept.
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.