Sikau

React · Day 3 · about 30 min

Props

Pass data into components.

One component, many cards

A Dish card is only useful if it can show *any* dish. props are the inputs to a component — like arguments to a function — so the same component can show different data.

Passing and reading props

function Dish({ name, price, spicy = false }) {
  return (
    <li>
      {name} — Rs {price} {spicy ? "🌶️" : ""}
    </li>
  );
}

export default function Menu() {
  return (
    <ul>
      <Dish name="Momo" price={180} />
      <Dish name="Chowmein" price={150} spicy />
      <Dish name="Thukpa" price={220} spicy={false} />
    </ul>
  );
}
  • Props flow one way: parent → child. A component must never change its own props.
  • Anything can be a prop: numbers, arrays, objects, functions, even other JSX.
  • The special prop children is whatever you put between the tags: <Card>Hello</Card>.
function Card({ title, children }) {
  return (
    <section style={{ border: "1px solid #ccc", padding: 12, borderRadius: 12 }}>
      <h3>{title}</h3>
      {children}
    </section>
  );
}

export default function App() {
  return (
    <Card title="Opening hours">
      <p>Every day, 8am–8pm</p>
    </Card>
  );
}

The rest of this lesson

  • Props are read-only inputsexplain
  • Designing good propsexplain
  • What's the price?predict
  • String or number?predict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React