Boyang Boyang - 2 months ago 5
React JSX Question

React - when to use props.children and when to add element to React.createElement?

I'm getting started with React. In library components I often see

props.children
being required prop (also required
child.key
). In tutorials I see you can put children nodes into
React.createElement(tag, [props], [children])
call.

So when to use which?

Answer

They are two sides to the same coin:

var MyComponent = React.createClass({
  propTypes: {
    summary: React.PropTypes.string,
    // Children are what we accept, and we display them in our <details>
    children: React.PropTypes.element
  },
  render: function() {
    return (<details>
      <summary>{this.props.summary}</summary>
      {this.props.children}
    <details>);
  }
});

React.createElement(
  MyComponent,
  {summary: 'Here is where we *use* children'},
  React.createElement('span', {}, 'Some more details')
);

// Final "HTML"
<details>
  <summary>Here is where we *use* children</summary>
  <span>Some more details</span>
</details>
Comments