DEV Community

Daniel Bellmas
Daniel Bellmas

Posted on

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 (
        <CommentBody {...comment}/>

        {hasComments && (
          <ul className={styles.comments}>
            { => (
              <li key={comment.index}>
                <Comment key={index} comment={comment} />
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 = () => (
    <Comment comment={nestedComments}/>
Enter fullscreen mode Exit fullscreen mode


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

Top comments (0)