FrontendDeveloper.in

React question detail

What is children prop?

The children 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.

A simple usage of children prop looks as below,

function MyDiv({ children }){
return (
{children}
);
}

export default function Greeting() {
return (
<MyDiv>
<span>{"Hello"}</span>
<span>{"World"}</span>
</MyDiv>
);
}

Here, everything inside <MyDiv>...</MyDiv> is passed as children to the custom div component.

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.

Back to all React questions
Get LinkedIn Premium at Rs 399