Design Patterns · Middle · Question 11 of 75

How do you render a comment tree of arbitrary depth?

function Comment({ comment }) {
  return (
    <li>
      {comment.text}
      {comment.replies.length > 0 && (
        <ul>{comment.replies.map(r => <Comment key={r.id} comment={r} />)}</ul>
      )}
    </li>
  );
}

Explanation

Nodes and leaves are handled the same way, so the component calls itself for its children. For very deep or large trees, add virtualization or "Show more", and store the data normalized.

Further reading

Problem with a question

Design Patterns · Middle · question 11

Test yourself

Take the Design Patterns · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz