I'm looking off of the reactjs tutorial on how to build a comment box with react. I get that we are mapping over data, but I cant understand this syntax and part of the code. Would be really helpful if you could explain exactly what is going on here. Specifically, why is props author={comment.author} within the Comment element tag itself and {comment.text} is not.
<Comment author={comment.author}>
{comment.text}
</Comment>
Context:
var data = [
{author: "Pete Hunt", text: "This is one comment"},
{author: "Jordan Walke", text: "This is *another* comment"}
];
var commentNodes = this.props.data.map(function (comment) {
return (
<Comment author={comment.author}>
{comment.text}
</Comment>
);
});
Firstly, we should understand, how
Commentis defined. From the ReactJS tutorial:The call to
React.createClassdefines new component, which could be rendered in the following way:As you can see,
{this.props.author}has been replaced withPete Hunt, defined asauthorproperty ofCommentcomponent, and{this.pros.children}- withComment's content (justThis is one commentin this case).Now we could move to
CommentListdeclaration. YourcommentNodesfunction is a part of this component, so, I'll show full definition:Here you can see
renderfunction, defined in terms ofcommentNotes(<div className="commentList"> {commentNodes} </div>). So, what doescommentNodesdo?It transforms each
commentobject intoCommentcomponent. Suppose, we havethis.props.datadefined as:Thus, calling
commentNodeswill create the following components:That will be rendered as:
UPD
This is pretty simple - by design. You could rewrite
Commentcomponent in the following way:And rewrite
CommentListas:Note also, passing comment text as
{this.props.children}allows you to createCommentwith nested elements, not only with text.