Props and Composition
💻 ReactPass data into components with props and compose small pieces into a page.
Props are the inputs of a component. They make one component reusable with different data.
- Pass and read props.
- Destructure props.
- Compose components together.
Passing Props
Add attributes to the component and read them from the props object.
function Badge({ label, tone = "neutral" }) {
return <span className={`badge badge-${tone}`}>{label}</span>;
}
function App() {
return (
<div>
<Badge label="Free" />
<Badge label="Premium" tone="gold" />
</div>
);
}Props Are Read-Only
A component must never change its own props. If a value needs to change, the parent owns it and passes a new value.
Children
The children prop holds whatever is placed between the opening and closing tags. It is how layout components work.
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
<Card title="Results">
<p>You passed 8 of 10 subjects.</p>
</Card>Practice
- Create a Button component with label and onClick props.
- Use children to build a reusable Panel component.
- Render a list of three Badge components.
Hands-on exercise
Create a StudentCard component that accepts name, level and score.
Render three different students from an array.
Highlight the score when it is 70 or above.
Recap
Props pass data down the tree. Components never change props, and children make layout components flexible.
Example
function Badge({ label, tone = "neutral" }) {
return <span className={`badge badge-${tone}`}>{label}</span>;
}
function App() {
return (
<div>
<Badge label="Free" />
<Badge label="Premium" tone="gold" />
</div>
);
}
Exercises
Render three different students from an array.
Highlight the score when it is 70 or above.
Expected Output
Three cards, with high scores styled differently.
Lesson Nav
React Course
0/9 lessons completed
- 1 Thinking in Components Tutorial
- 2 Props and Composition Tutorial
- 3 State and Events Tutorial
- 4 Lists, Keys and Conditional Rendering Tutorial
- 5 Forms in React Tutorial
- 6 Effects and Data Fetching Tutorial
- 7 Routing and Layouts Tutorial
- 8 Context and Shared State Tutorial
- 9 Project: A Student Dashboard Project