Given the below array, I'd like to render comments
in a threaded manner by making use of parentId
.
comments: [
{
id: 1,
parentId: null
},
{
id: 2,
parentId: 1
},
{
id: 3,
parentId: 1
},
{
id: 4,
parentId: 3
},
{
id: 5,
parentId: 4
}
]
I thought with the below components I'd be able to recurse through the comments, but the output is not what I'd expect (it seems to be rendering a new <ul>
element for every comment.) I'm a bit new to react and javascript, so maybe I'm not implementing the recursion correctly, or should comments
be structured differently?
const Comment = (props) => (
<li>
{props.comment.id}
{props.comment.children.length > 0 ?
<Comments comments={props.comment.children}/>
: null }
</li>
);
const Comments = (props) => (
<ul>
{props.comments.map((comment) => {
comment.children = _.filter(props.comments, {'parentId': comment.id});
return <Comment key={comment.id} comment={comment}/>
})}
</ul>
);