FrontendPro

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.

  1. Write buildTree(comments): return the top-level comments, each with a replies array, nested to any depth, preserving the original order. Do it in O(n).
  2. 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 by currentUser under that comment;
    • a comment with replies shows a Hide replies (n) button, where n is 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.

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.

Infinite Nested Comments | React Js Interview Questions | Machine Coding Interview ExperienceFrontend with Aman on YouTubeOpen on YouTube
Building a Nested Comments System with ReactShadee Merhi on YouTubeOpen on YouTube

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.

All 150 answersOne payment, yours forever