Real Life Example - Recursive Components

danielbellmas

Daniel Bellmas

Posted on April 24, 2022

Real Life Example - Recursive Components

Following my last article about displaying comments a recursive way, where we turned a flat array into a recursive object (tree), here is the UI implementation in React.

The end result I wanted to achieve looks something like this: Recursive comments

The first thing we can see is that every comment body is pretty similar, which, for every web dev, screams GENERIC COMPONENT!


The Recursive Component

const Comment = ({ comment }) => {
    const { index, comments } = comment;

    const hasComments = !!comments.length;

    return (
      <React.Fragment>
        <CommentBody {...comment}/>

        {hasComments && (
          <ul className={styles.comments}>
            {comments.map(comment => (
              <li key={comment.index}>
                <Comment key={index} comment={comment} />
              </li>
            ))}
          </ul>
        )}
      </React.Fragment>
    );
  };
Enter fullscreen mode Exit fullscreen mode

ā€”ā€”

A Breakdown of the Code

The CommentBody component is the UI of a single comment, and if it has sub comments then we'll render a ul with all of the sub comments, and if one of those comments too has comments then we'll render those too and so forth...

Every recursion has to have a stopping condition.
Here, hasComments is checking if a comment has more comments inside.

To use the component we need to pass a recursive object to it, in this case, it will look something like this:

const nestedComments = {
  index: 0,
  title: "'title1',"
  comments: [
    {
      index: 1,
      title: 'title2'
    },
    {
      index: 2,
      title: "'title3',"
      comments: [
        {
          index: 3,
          title: 'title4'
        }
      ]
    }
  ]
};

const Comments = () => (
  <section>
    <Comment comment={nestedComments}/>
  </section>
);
Enter fullscreen mode Exit fullscreen mode

Conclusion

We can see that a recursive design requires a -> recursive component which requires -> recursive data.

šŸ’– šŸ’Ŗ šŸ™… šŸš©
danielbellmas
Daniel Bellmas

Posted on April 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related