React Basics: Build Interactive Interfaces
Components and Props
In this lesson you will
- Pass data into a component with props
- Use default values and children
- Explain why props are read-only
Introduction
A component that always shows the same thing is not very useful. Props (short for properties) let a parent tell a component what to show, like arguments to a function.
The simple explanation
Props are the inputs of a component. The parent sets them, and the child reads them.
Passing props
React (JSX)
function Greeting({ name, mood = "happy" }) {
return (
<p>
Hello, {name}! You look {mood} today.
</p>
);
}
function App() {
return (
<div>
<Greeting name="Sam" />
<Greeting name="Priya" mood="excited" />
</div>
);
}The curly braces in the function's parameter pull out the props. mood = "happy" gives a default when none is passed. This renders "Hello, Sam! You look happy today." and "Hello, Priya! You look excited today."
To pass something that is not a plain string, use curly braces: <Price amount={9.99} /> or <List items={myArray} />.
Quick quiz
How does a parent component give data to a child?
Children
Whatever you place between a component's opening and closing tags arrives as the special prop children:
React (JSX)
function Card({ title, children }) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}
function App() {
return (
<Card title="Today">
<p>Learn about props.</p>
</Card>
);
}Card provides the frame, and the parent decides what goes inside. This is how many layout components work.
Props are read-only
A component must never change its own props. Data flows down from parent to child. If a value needs to change, it belongs in state, the next lesson.
Try it yourself
Create a Badge component with a label prop and an optional color prop with a default. Show three badges with different labels.
Summary
- Props are inputs passed from parent to child, like function arguments.
- Use curly braces for non-string values, and
childrenfor nested content. - Props are read-only. Changing data is the job of state.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading