In React, when you nest elements inside a component tag, those nested elements are automatically packaged and passed to the component via a reserved prop named children.
This enables component composition, a core architecture design principle in React that allows you to construct flexible, reusable container components without knowing what content will be placed inside them ahead of time.
1// Reusable Container Component
2functionModalDialog({ title, children }){
3return(
4<divclassName="modal-backdrop">
5<divclassName="modal-card">
6<headerclassName="modal-header">
7<h2>{title}</h2>
8</header>
9<divclassName="modal-body">
10{children}{/* Render whatever is nested inside */}
11</div>
12</div>
13</div>
14);
15}
Consuming the Component:
1functionApp(){
2return(
3<ModalDialogtitle="Confirm Enrollment">
4<p>Are you sure you want to register for Full-Stack Web Development?</p>
5<divclassName="button-row">
6<buttonclassName="btn-cancel">Cancel</button>
7<buttonclassName="btn-confirm">Confirm</button>
8</div>
9</ModalDialog>
10);
11}
In this example, the <p> and the <div> are passed into ModalDialog as props.children and rendered inside <div className="modal-body">.
2. Containment vs Specialization
React recommends composition over inheritance. You never need to use object-oriented class inheritance (class SpecialDialog extends Dialog) in React. Instead, you compose components using containment and specialization.
Containment (Generic Shells)
A generic shell doesn't know its children in advance (e.g., Card, Sidebar, Panel):
Specific components render a generic shell configured with pre-defined props:
1functionWelcomeCard({ studentName }){
2return(
3<CardclassName="card-welcome">
4<h3>Welcome,{studentName}!</h3>
5<p>Pick up where you left off in your curriculum.</p>
6</Card>
7);
8}
3. Multiple Content Slots via Named Props
While children is ideal for the primary body content, sometimes a component needs multiple designated slots (e.g., a header, a body, and an action footer).
You are not restricted to children! You can pass any JSX element or component as a standard named prop: