The
prop is a special prop in React used to pass elements between the opening and closing tags of a component. It is commonly used in layout and wrapper componnents.children
A simple usage of children prop looks as below,
function MyDiv({ children }){return (<div>{children}</div>;);}export default function Greeting() {return (<MyDiv><span>{"Hello"}</span><span>{"World"}</span></MyDiv>);}
Here, everything inside
is passed as children to the custom div component.<MyDiv>...</MyDiv>
The children can be text, JSX elements, fragments, arrays and functions(for advance use case like render props).
See Class
const MyDiv = React.createClass({render: function () {return <div>{this.props.children}</div>;},});ReactDOM.render(<MyDiv><span>{"Hello"}</span><span>{"World"}</span></MyDiv>,node);
Note: There are several methods available in the legacy React API to work with this prop. These include
,React.Children.map
,React.Children.forEach
,React.Children.count
,React.Children.only
.React.Children.toArray