Real Life Example - Recursive Components
Daniel Bellmas
Posted on April 24, 2022
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:
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>
);
};
āā
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>
);
Conclusion
We can see that a recursive design requires a -> recursive component which requires -> recursive data.
Posted on April 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.