Lets say our component structure is as follows:
CommentList is defined as:
var CommentList = React.createClass({
render: function() {
return (
<div className="commentList">
<Comment author="Pete Hunt">This is one comment</Comment>
</div>
);
}
});
and Comment defined as
var Comment = React.createClass({
render: function() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.children}
</div>
);
}
});
It seems a bit strange that this.props.children is selecting the text "This is one comment". Why is it called "children", shouldn't it be "innerHTML" or something? I feel like I'm missing something.
What you wrap between a component, is not its inner HTML, but is wrapped into a ReactElement, and passed as a prop in props.children.
When you use JSX syntax, whatever is inserted inside the tags of an element, becomes the element 0 of the props.children array of the component. When there is just one child, no array is created and props.children points to the only element. From the docs:
However, when there is only a single child, this.props.children will be the single child component itself without the array wrapper. This saves an array allocation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With