Chapter 3 of 4

Children and Composition

The children prop, and using components as slots instead of piling on options.

Anything you put between a component's opening and closing tags arrives as a prop named children. This is what makes React components composable.

function Card({ title, children }) {
  return (
    <section className="card">
      <h3>{title}</h3>
      <div className="card-body">{children}</div>
    </section>
  );
}

<Card title="Account">
  <p>You are signed in as ada@example.com</p>
  <button>Sign out</button>
</Card>

Composition beats configuration

When a component grows a long list of boolean props, that is usually a sign it should accept content instead of options.

// Configuration: every new variation needs another prop
<Dialog
  hasHeader
  hasFooter
  showCloseButton
  footerButtonLabel="Save"
/>

// Composition: the caller supplies whatever it needs
<Dialog>
  <Dialog.Header>Edit profile</Dialog.Header>
  <Dialog.Body><ProfileForm /></Dialog.Body>
  <Dialog.Footer><button>Save</button></Dialog.Footer>
</Dialog>

Multiple slots

children is just a prop, so nothing stops you from passing several pieces of UI under different names.

function SplitPane({ left, right }) {
  return (
    <div className="split">
      <div className="left">{left}</div>
      <div className="right">{right}</div>
    </div>
  );
}

<SplitPane left={<FileTree />} right={<Editor />} />