Components and JSX · Lesson 3 of 21
Props
Passing data into components, children, and default values.
Props are how a parent passes data to a child, like a function's parameters. They arrive as one object, usually destructured right in the signature.
function CourseCard({ title, hours, price = 0, tags = [] }) {
return (
<div style={{ border: "1px solid #ccc", borderRadius: 12, padding: 12, marginBottom: 8 }}>
<h3 style={{ margin: 0 }}>{title}</h3>
<p style={{ margin: "4px 0" }}>{hours} hours · {price === 0 ? "Free" : price + " EGP"}</p>
<small>{tags.join(", ")}</small>
</div>
)
}
function App() {
return (
<>
<CourseCard title="HTML & CSS" hours={12} tags={["web", "beginner"]} />
<CourseCard title="React" hours={24} price={600} tags={["web"]} />
</>
)
}Note: text is passed in quotes, title="React"; anything else (a number, array, object, function) goes in { }. price = 0 is a default when the parent sends nothing.
children
function Panel({ title, children }) {
return (
<section style={{ background: "#eef6ff", padding: 12, borderRadius: 12 }}>
<strong>{title}</strong>
<div>{children}</div>
</section>
)
}
function App() {
return (
<Panel title="Tip">
<p>Anything between the tags arrives as <code>children</code>.</p>
</Panel>
)
}App: <CourseCard title="React" hours={24} />
props = { title: "React", hours: 24 }
CourseCard reads and renders
Data flows one way: from parent to child.
Quick question
How do you pass 24 as a prop so it arrives as a number, not text?
Exercise
Finish Greeting so it shows Hi, NAME!, with NAME defaulting to friend. The page should show Hi, Mariam! then Hi, friend!.
Hi, Mariam! Hi, friend!
function Greeting(props) {
return <p>Hi!</p>
}
function App() {
return (
<div>
<Greeting name="Mariam" />
<Greeting />
</div>
)
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.