Recursion in React


Author: Rahul Krishna

TLDR;


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:


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


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


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


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


This project is maintained by rahulakrishna on GitHub. You can find me on Mastodon @_thisdot@mastodon.social