DevPath · Learn to code ESPTEN

Composition: children and slots

props.children and container components

Compose instead of configure

So far you passed data to a component with regular props (title, name...). But often what you want to pass is not a piece of data, but another chunk of UI: what you write between the opening and closing tags of the component.

React delivers that content through a special prop: children.

function Card({ children }) {
  return <div className="card">{children}</div>;
}

And it is used by wrapping any markup:

<Card>
  <h2>Hello</h2>
  <p>I'm the content of the card.</p>
</Card>

Here Card doesn't know nor care what's inside: it just wraps it with a border, some padding or a shadow. That makes it a reusable container component: the same Card works for text, a form or an image.

Why it's so useful

function Layout({ children }) {
  return (
    <main className="layout">
      <header>My App</header>
      <section>{children}</section>
    </main>
  );
}

function App() {
  return (
    <Layout>
      <h1>Home page</h1>
    </Layout>
  );
}

children can be a single element, several, text, or even null. React treats it like any other prop: you render it with {children} wherever you want.

Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Slots: passing elements via props →