Sikau

React · Day 20 · about 30 min

Composition patterns

Build flexible components with children and slots.

Flexible, not configurable

A Card with fifteen props for every possible layout becomes a nightmare. React's answer is composition: let the parent pass in pieces of UI (children, or named slots) so one small component fits many uses.

children, slots and wrappers

function Modal({ title, footer, children }) {
  return (
    <div role="dialog" aria-label={title} style={{ border: "1px solid #ccc", borderRadius: 12, padding: 16 }}>
      <h2>{title}</h2>
      <div>{children}</div>
      <footer style={{ marginTop: 12 }}>{footer}</footer>
    </div>
  );
}

export default function App() {
  return (
    <Modal title="Delete order?" footer={<><button>Cancel</button> <button>Delete</button></>}>
      <p>This can't be undone.</p>
    </Modal>
  );
}
  • Prefer composition over inheritance: React components never extend each other.
  • Layout components (Stack, Grid, Page) wrap children and handle spacing.
  • Avoid deeply nested props objects; pass JSX instead.

The rest of this lesson

  • Children instead of configurationexplain
  • Wrappers and layout componentsexplain
  • Where does it render?predict
  • Where does it go?predict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React