Props and state
Compose wrappers with children
Render the nested content a parent places between a component opening and closing tag.
When you nest JSX between a component’s opening and closing tags, that content arrives in the special children prop.
function Panel({ title, children }) {
return (
<section className="panel">
<h2>{title}</h2>
{children}
</section>
)
}
The parent supplies the content:
<Panel title="Account">
<p>Signed in as [email protected]</p>
<button>Sign out</button>
</Panel>
The page renders a section with the title Account, then the paragraph and button inside it.
Panel controls the shared structure. It does not need a separate prop for every paragraph or button that might appear inside it.
This is composition. It is often clearer than adding configuration props such as showButton, buttonText, and bodyType for every variation.
You can also pass multiple children as an array, or a single string as children. React treats them the same way inside the wrapper.
Children are still values from the parent render. The wrapper can place them, hide them, or surround them with markup. It should not assume a specific child structure unless that is part of a documented component contract.
Use semantic wrappers. A panel that represents an independent topic may be a section. A purely visual wrapper may be a div.
You can also inspect children in React DevTools. The nested markup shows up as the prop value, which makes debugging composition easier than tracing ten optional boolean props.
You can pass elements as props too, but children is the conventional name when the parent wraps content between tags.
Layout components like Panel, Card, and Layout are the most common place you will reach for children in real apps.
Create a second Panel containing a form. Notice that the wrapper stays reusable without knowing form details.
Lesson completed