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
Comment
is defined. From the ReactJS tutorial:The call to
React.createClass
defines new component, which could be rendered in the following way:As you can see,
{this.props.author}
has been replaced withPete Hunt
, defined asauthor
property ofComment
component, and{this.pros.children}
- withComment
's content (justThis is one comment
in this case).Now we could move to
CommentList
declaration. YourcommentNodes
function is a part of this component, so, I'll show full definition:Here you can see
render
function, defined in terms ofcommentNotes
(<div className="commentList"> {commentNodes} </div>
). So, what doescommentNodes
do?It transforms each
comment
object intoComment
component. Suppose, we havethis.props.data
defined as:Thus, calling
commentNodes
will create the following components:That will be rendered as:
UPD
This is pretty simple - by design. You could rewrite
Comment
component in the following way:And rewrite
CommentList
as:Note also, passing comment text as
{this.props.children}
allows you to createComment
with nested elements, not only with text.