Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.3Passing data with props

Props are values passed from a parent to a child. They make one component reusable with different data, in the same way that function parameters make a function reusable.

Receiving props

JSX
function TaskItem({
  title,
  complete = false
}) {
  const className = complete
    ? "task task--complete"
    : "task";

  return (
    <li className={className}>
      <span className="task__title">
        {title}
      </span>
    </li>
  );
}

<TaskItem
  title="Learn props"
  complete={true}
/>

String props may use quotes. Numbers, booleans, arrays, objects and functions go inside braces. Destructuring in the parameter list makes the component's inputs easy to see.

The children prop

Markup nested between a component's opening and closing tags arrives as children. It is useful for layout components such as cards, panels and dialogs that provide structure around content.

JSX
function Panel({ children }) {
  return (
    <section className="panel">
      {children}
    </section>
  );
}

Props are read-only

A child must not change its props. If a value must change, its owner stores it as state and passes down a new value. This one-way data flow makes updates easier to trace.

Follow the data flow

React turns <TaskItem title="Learn props" complete={true} /> into one props object. Destructuring gives the component local variables named title and complete. The default applies only when complete is missing or undefined; it does not replace an explicit false.

Prop names form an interface. If the parent sends isComplete but the child reads complete, the value is missing. React cannot infer that the names mean the same thing.

Challenge: configure TaskItem

Add priority and dueDate props. Give priority a default of normal, include it in the class name and render the date only when supplied. Create three differently configured items.

Hint

Conditional content can use {dueDate && <time>{dueDate}</time>}.

Feedback 👍
Comments are sent via email to me.