Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.props.children selecting innerHTML

Tags:

reactjs

Lets say our component structure is as follows:

  • CommentList
    • Comment

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.

like image 574
Tony54 Avatar asked Aug 11 '26 02:08

Tony54


1 Answers

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.

like image 151
gcedo Avatar answered Aug 12 '26 19:08

gcedo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!