Build reusable container components with the children prop and split your screens into clear responsibilities.
Open this lesson in KodokonSome components do not know their content in advance: a card, a modal window, a layout. React solves this with the special children prop: everything you place between a component's opening and closing tags is handed to it, ready to be inserted wherever it wants. The container handles the frame, the caller supplies the content.
function Card({ children }) {
return <section className="card">{children}</section>;
}
function App() {
return (
<Card>
<h2>Invoice #1024</h2>
<p>Amount: €49.90</p>
</Card>
);
}When a single slot is not enough, pass JSX through named props: a title, a footer, an action bar. A prop can receive a React element just like any other value. You get several “slots”, each one clearly named.
function Modal({ title, footer, children }) {
return (
<div className="modal">
<header>{title}</header>
<div className="modal-body">{children}</div>
<footer>{footer}</footer>
</div>
);
}Composition also guides splitting. A component should have one identifiable responsibility: displaying a user row, laying out a list. As soon as a component accumulates several roles, extract sub-components: each one becomes shorter, easier to test, and reusable elsewhere.
function UserList({ users }) {
return (
<ul>
{users.map((user) => (
<UserRow key={user.id} user={user} />
))}
</ul>
);
}
function UserRow({ user }) {
return (
<li>
<strong>{user.name}</strong> - {user.email}
</li>
);
}children prop receive?children?