I have the following json:
{
\"comments\":[
{
\"id\":1,
\"comment_text\":\"asdasdadasdsadsadadsa\",
\"author\":\"adsfasdasdsad\",
This is easier to do with just the one component if you make it responsible for rendering its own children recursively:
var Comment = React.createClass({
render() {
var comment = this.props.comment
return <div>
<div dangerouslySetInnerHTML={{__html: comment.comment_text}}/>
{comment.children.length > 0 && comment.children.map((child) => {
return <Comment key={child.id} comment={child}/>
})}
</div>
}
})
If you want to do this without nesting the components so you're just rendering a flat list of <Comment>
s, you can linearise the tree of comments into a list first, e.g.
function flattenComments(comments, flatComments, level) {
for (var i = 0, l = comments.length; i < l; i++) {
var comment = comments[i]
flatComments.push({comment: comment, level: level})
if (comment.children.length > 0) {
flattenComments(comment.children, flatComments, level + 1)
}
}
}
var flatComments = []
flattenComments(comments, flatComments, 0)
var renderedComments = flatComments.map((props) => {
return <Comment {...props}/>
})
You need two components: Comments and Comment.
Comment = React.createClass({
render: function(){
var comment = this.props.comment;
return <div>
<p>{comment.author} says {comment.comment_text}</p>
<Comments comments={comment.children} />
</div>
}
});
Comments = React.createClass({
render: function(){
return <div>
{this.props.comments.map(function(comment){
return <Comment key={comment.id} comment={comment} />
})
</div>
}
});
The Comment renders Comments, which in turn can render Comment nodes, etc. This recursively builds the comment structure.