Course outline · 0% complete

0/28 lessons0%

Course overview →

Passing data with props

lesson 3-1 · ~10 min · 7/28

Quiz

Warm-up from lesson 2-3: you composed App from Header and two TaskItem components. What was awkward about those TaskItems?

Passing data with props

Props (short for properties) are the inputs of a component. You pass them where you use the component, written like HTML attributes, and React collects them into a single object that becomes the function's first parameter:

function TaskItem(props) {
  return <li>{props.title}</li>;
}

function App() {
  return (
    <ul>
      <TaskItem title="Water the plants" />
      <TaskItem title="Pay rent" />
    </ul>
  );
}

<TaskItem title="Pay rent" /> makes React call TaskItem({ title: "Pay rent" }). Strings use quotes. Anything else, numbers, booleans, arrays, objects, functions, goes in braces:

<TaskItem title="Pay rent" done={true} priority={2} />
AppTaskItem{ title: "Water plants" }TaskItem{ title: "Pay rent" }title="Water plants"title="Pay rent"same component, different props, different output
Props flow down the tree. App renders TaskItem twice, each call receives its own props object, so one component produces two different list items.

Code exercise · javascript

Props with the JSX stripped away. A component is a function, props is just its argument object. Run it and match each line of output to each call.

Destructuring props

Writing props.title everywhere gets noisy. In Advanced JavaScript you learned object destructuring, and React code uses it in the parameter list almost universally:

function TaskItem({ title, done }) {
  return <li>{done ? "✓ " : ""}{title}</li>;
}

Same function, the { title, done } pattern pulls the fields out of the props object immediately. Read any real React codebase and this is the shape you will see.

Code exercise · javascript

Your turn. Write Badge using destructuring in the parameter list, returning "<span>LABEL: COUNT</span>". The two calls should print the expected output.