FrontendInterviews.dev

Loading problem…

81. Comments Thread

Medium•

Build a Comments Thread component in React that renders nested replies and supports branch-level interactions (reply, collapse/expand) without corrupting tree state.

Requirements

1. Recursive Rendering

  • Render comments as a recursive tree (root -> replies -> deeper replies).
  • Each node displays author, timestamp, and body.
  • Nested levels should be visually indented.

2. Reply Composer Per Node

  • Every comment has a Reply action.
  • Clicking Reply opens an inline composer scoped to that comment.
  • Submitting inserts a new child under that parent.
  • Cancel closes composer without mutating data.

3. Collapse / Expand Branches

  • Any comment with children can be collapsed/expanded.
  • Collapsing hides descendants only (parent remains visible).
  • Collapse state must be keyed by stable comment.id (never array index).

4. Immutable Tree Updates

  • Reply insertion must be immutable (no in-place push/splice on existing state).
  • Preserve sibling order and untouched branches.
  • Multiple inserts at different depths must remain deterministic.

5. Data Contract

interface CommentNode {
  id: string;
  author: string;
  body: string;
  createdAt: string;
  replies?: CommentNode[];
}

interface CommentsThreadProps {
  comments: CommentNode[];
  onChange: (next: CommentNode[]) => void;
}

6. Example Seed Data

const seed: CommentNode[] = [
  {
    id: "c1",
    author: "Ava",
    body: "Great write-up.",
    createdAt: "2026-04-01T09:00:00.000Z",
    replies: [
      {
        id: "c1-1",
        author: "Noah",
        body: "Agreed, especially the caching part.",
        createdAt: "2026-04-01T09:05:00.000Z"
      }
    ]
  }
];

Constraints

  • Support at least 3+ nesting levels.
  • Reply insertion must be immutable and parent-id targeted.
  • Collapse state must remain stable after inserts.
  • Reject empty or whitespace-only replies.
  • Keep branch interactions responsive with 100+ comments.