Topic 10 of 54
The children Prop
Overview
Sometimes you don't know what content a component will hold ahead of time. Think of a 'Card' component or a 'Modal' dialogue. You want the outer layout, but the inner content should be entirely customizable by the parent. React provides a special prop called `children` that captures whatever you place *between* the opening and closing tags of a component.
Syntax
The `children` prop allows for component 'Composition'. It lets you build generic layout wrappers without needing to pass dozens of specific props.
Using the children Prop
jsx
// 1. The wrapper component receives 'children'
function Card({ title, children }) {
return (
<div className="card-container">
<h2 className="card-title">{title}</h2>
{/* 2. Render the injected content here */}
<div className="card-body">
{children}
</div>
</div>
);
}
// 3. The parent injects content between the tags
function App() {
return (
<Card title="User Profile">
{/* Everything here becomes the 'children' prop! */}
<img src="avatar.jpg" />
<p>Software Engineer from India.</p>
<button>Follow</button>
</Card>
);
}Common Pitfalls
- Trying to mutate or read specific properties off the `children` prop directly. Treat it as a black box that you simply render.
Interview Tips
- Component Composition (using `children`) is the React way to avoid 'Prop Drilling'. If an interviewer asks how to avoid passing props down 5 levels, suggest passing the component directly as `children`.
Real-World Example
A reusable Modal/Dialog component is the classic use-case for the children prop.
example
jsx
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null;
return (
<div className="modal-backdrop">
<div className="modal-content">
<button className="close-btn" onClick={onClose}>X</button>
{/* The dynamic content goes here */}
{children}
</div>
</div>
);
}
// Usage
<Modal isOpen={true} onClose={closeModal}>
<h2>Confirm Deletion</h2>
<p>Are you sure you want to delete this file?</p>
<button>Yes, Delete</button>
</Modal>