Props work well when you know what kind of data a component needs: a title, a number, a flag. Some components are frames for any content. A card, a panel or a dialog shouldn't care what goes inside it.
For that, React has a special prop called children. Whatever you put between
a component's opening and closing tags arrives as children:
<Card title="Props">
<p>Props pass data from a parent to a child.</p>
</Card>Inside Card, {children} marks where that content goes.
npm install and npm run dev. Both cards use the same Card component. One wraps a paragraph and the other
wraps a numbered list. Card supplies the frame and the heading, and the
parent decides what goes inside:
export default function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}Predict
Add a third card to App.jsx with no children:
<Card title="Empty" />What does it show? Run it to check.
Check your prediction
A card with the heading Empty and nothing under it. Without content between
the tags, children is undefined, and React shows nothing for it.
Composition
Building bigger pieces from smaller ones like this is called composition.
It's how React apps grow: App is made of cards, a card is made of a heading
and its children, and each piece stays small enough to read in one go.
Use children when the content varies a lot from one use to the next. Use
ordinary props when the component needs specific values it formats itself,
like DayCard's minutes.
Your turn
A Tip box
Write a Tip component that shows the word Tip: in bold, followed by its
children, inside a <p>. Use it twice in App:
- Tip: Run after every small change.
- Tip: Read the console before the code.
npm install and npm run dev. Hint 1: the idea
Tip receives { children } and returns one <p>. Bold text is
<strong>...</strong>.
Hint 2: a first step
<Tip>Run after every small change.</Tip>. Text between the tags is children
too, not only elements.
Show one solution
function Tip({ children }) {
return (
<p>
<strong>Tip:</strong> {children}
</p>
);
}And in App:
<Tip>Run after every small change.</Tip>
<Tip>Read the console before the code.</Tip>You can define Tip in App.jsx above App, or in its own file with a
default export.
Completion is saved in this browser only. It does not measure mastery.