Recently I was inspired by the minimalist look and feel of the Hacker News comments section, and I wanted to try recreating it with React: The goal of

React: Recreating the Hacker News Comments Section

submited by
Style Pass
2021-07-08 04:30:38

Recently I was inspired by the minimalist look and feel of the Hacker News comments section, and I wanted to try recreating it with React:

The goal of this post is to show you how to recreate the demo above, while allowing the comments section to be generated from any list of comments you give it, so long as they look somewhat like this:

In other words, our solution will be able to recursively generate a tree of comments from a flat array of comments data, so long as they contain the right information to do so (such as parentId if the comment is a reply to an existing comment).

Now let's make sure the comments are sorted and nested nicely as a tree of replies, and not just a long, visually confusing list. To do this, we'll need to create a function that converts our flat array of comments into a comment tree.

Luckily for us, a quick search of "convert flat array to tree javascript" into Google leads us to a popular Stack Overflow question, and a top answer that seems to have exactly what we need!

Leave a Comment