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>
);
}- ✓Correct answer: With a recursive component - the Composite pattern for UI
- 2Only as a flat list; recursion is forbidden in React
- 3With a
useEffectthat inserts nested replies into the DOM
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.