Component Children

There is one prop that gets special treatment unlike all the others. That, my friend, is this.props.children.

Children allow you to pass components as data to other components, just like any other prop you use. The special thing about children is that React provides support through its ReactElement API and JSX. XML children translate perfectly to React children!

var MyDiv = React.createClass({
  render: function() {
    return <div>{this.props.children}</div>;
  }
});

ReactDOM.render(
  <MyDiv>
    <span>Hello</span>
    <span>World</span>
  </MyDiv>,
  node
);

this.props.children

If you look at the JSX transform, you'll find that XML children are appended as arguments to the React.createElement call. These extra arguments are passed to the component via this.props.children.

Most often, your component will render content and include the children in the render output. This is a great way to create UI components, like cards, headers, and buttons.

Occasionally, you may want to interact with the children, maybe mutating or separating them. Be careful here and remember to treat this.props.children as an opaque data structure. Instead of working with this.props.children directly, use the React.Children utilities to work with children. In this example, we create a component that takes its children and renders a list, wrapping each child in an <li>.

For the curious

React's native DOM components use the children prop just like you do in your components. When you write <div>Hello</div>, you are passing the text child Hello to the native DIV component. Take a look at the source!

Advanced Reading

_
Read Another

Optimizing with shouldComponentUpdate

We'll take a look at how to squeeze performance with shouldComponentUpdate, a hint we can give components to make them smarter (or buggier).

Liked this?

Subscribe

Subscribe for a range of articles from React basics to advanced topics such as performance optimization and deep dives in the React source code.