Skip to the workspace
Pebellslearn by building
Components and JSX  ›  Capstone Project

Composition and children

Composition 15 minComposition builds bigger components by nesting smaller ones, using the children prop and other props to leave slots that the parent fills in.

react / Composition and children

Explore each scene at your own pace.

01 · The rule

The rule

Composition and children

The reading list now needs a few boxes that all look alike — a border, some padding, a title bar — but hold completely different things. You could write BookBox, SearchBox and StatsBox. Or you could write the box once and let each parent decide what goes inside.

The rule

Build big from small; leave a slot, and let the parent fill it.

Build big from small. Components are combined by nesting them, not by inheriting from each other. React has no need for "a FancyCard that extends Card"; you put a Card inside something else instead.

Leave a slot. Whatever a parent writes between a component's opening and closing tags arrives as a special prop called children:

function Panel({ title, children }) {
  return (
    <section className="panel">
      <h2 className="panel-title">{title}</h2>
      <div className="panel-body">{children}</div>
    </section>
  );
}

Let the parent fill it:

export default function App() {
  return (
    <main>
      <Panel title="My books">
        <BookCard title="Dune" author="Frank Herbert" pages={412} />
      </Panel>
      <Panel title="Stats">
        <p>2 books, 722 pages</p>
      </Panel>
    </main>
  );
}

Panel has no idea what it contains, and that is exactly why it is reusable. You can leave more than one slot, too: any prop can hold JSX, as in <Layout sidebar={<Filters />} main={<BookList />} />.

A pleasant side effect: because App places BookCard directly inside the panel, it passes the book's data straight to BookCard. Panel never has to receive and forward props it does not care about.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.