DevPath · Learn to code ESPTEN

Composition: children and slots

Slots: passing elements via props

More than one hole

children is great when there is one place to put content. But sometimes a component has several zones you want to fill: a header, a body, an actions bar... We call those zones slots (holes).

The solution: since in JSX an element is just another value, you can pass JSX through regular props, not only via children.

function Panel({ title, actions, children }) {
  return (
    <section className="panel">
      <header>{title}</header>
      <main>{children}</main>
      <footer>{actions}</footer>
    </section>
  );
}

Each prop is a hole that the caller fills with whatever markup they want:

<Panel
  title={<h2>Settings</h2>}
  actions={<button>Save</button>}
>
  <p>Main content of the panel.</p>
</Panel>

children vs slots via props

<ConfirmDialog
  title="Delete file?"
  cancel={<button>No</button>}
  confirm={<button>Yes, delete</button>}
/>

A slot can be any React node: a string, a number, a JSX element or even another already-built component. You decide which <header>, <aside> or <footer> you place it in.

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 →
← props.children and container componentsComposition vs inheritance →