InterviewHubPRO
Section Overview
Q26

Question 26 of 445

Part 1: Core React, JSX & Component Architecture (1 - 77)

6%
React & Modern Frontend (445 Qs)•Part 1: Core React, JSX & Component Architecture (1 - 77)

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,

jsx
function MyDiv({ children }){
 return (
   <div>
     {children}
   </div>;
 );
}

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).

<details><summary><b>See Class</b></summary> <p>
jsx
const MyDiv = React.createClass({
render: function () {
 return <div>{this.props.children}</div>;
},
});

ReactDOM.render(
<MyDiv>
 <span>{"Hello"}</span>
 <span>{"World"}</span>
</MyDiv>,
node
);
</p> </details>

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.