Recursion in React

TLDR; Link to heading


TIL that you can have recursive components in React!


So while thinking in React, it may not immediately occur that you can call a **parent** inside the **child!** But it is possible

Consider a Data Structure like this: Link to heading


const comments = [
  {
    content: "Comment 1",
    level: 0,
    comments: [
      {
        content: "Comment 1 > 1",
        level: 1,
        comments: [
          {
            content: "Comment 1 > 1 > 1",
            level: 2,
            comments: [],
          },
        ],
      },
      {
        content: "Comment 1 > 2",
        level: 1,
        comments: [],
      },
    ],
  },
  {
    content: "Comment 2",
    level: 0,
    comments: [],
  },
];

Doing this in Javascript Link to heading


function displayComments(comments) {
  return comments.reduce((acc, comment) => {
    const prefix = Array(comment.level)
      .fill("|")
      .reduce((acc, item) => `${acc} ${item}`, "");

    const moreComments = displayComments(comment.comments);

    const stringToReturn = `${prefix} ${comment.content} \n ${moreComments}`;
    return `${acc} ${stringToReturn}`;
  }, "");
}

Result:

Javascript Result

Doing this in React Link to heading


function Comment({ comment }) {
  const prefix = Array(comment.level)
    .fill("|")
    .reduce((acc, item) => `${acc} ${item}`, "");
  return (
    <div>
      {prefix} {comment.content}
      <Comments comments={comment.comments} />
    </div>
  );
}

export default function Comments({ comments }) {
  return comments.map((comment) => {
    return <Comment comment={comment} />;
  });
}

Result:

React Result

Actual example of rendering a comment tree Link to heading


It’s unlikely we’ll be using | prefixes when actually building a comment tree. We’ll more likely be playing around with padding and margin.

Here’s a code example of actual comment tree rendering in React with TailwindCSS: https://github.com/rahulakrishna/hackrmn/blob/master/src/app/[storylist]/comments/[commentid]/comment-block.js

Untitled

References Link to heading