~/hackweb.dev
Component Composition
Quiz
...

Component Composition

intermediate · updated Tue Sep 08 2026Contribute

Combine components using children, layout patterns, and composition.

Component Composition

Composition lets you build complex UIs by combining small, reusable pieces.

The children Prop

Every component receives children — the content between its tags:

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

<Card>
  <h2>Title</h2>
  <p>Content goes here.</p>
</Card>

Layout Components

Wrap shared structure in layout components:

function PageLayout({ children }) {
  return (
    <div className="layout">
      <header>Nav</header>
      <main>{children}</main>
      <footer>Footer</footer>
    </div>
  );
}

<PageLayout>
  <h1>Home</h1>
</PageLayout>

Slot Pattern

Pass specific pieces as named props:

function Modal({ title, body, footer }) {
  return (
    <div className="modal">
      <h2>{title}</h2>
      <div>{body}</div>
      <div>{footer}</div>
    </div>
  );
}

<Modal
  title="Confirm"
  body={<p>Are you sure?</p>}
  footer={<button>OK</button>}
/>

Extracting Reusable Layouts

Combine composition with props for flexible patterns:

function Sidebar({ children, side = "left" }) {
  return (
    <aside className={`sidebar sidebar-${side}`}>
      {children}
    </aside>
  );
}

Best Practices

  1. Favor composition over inheritance
  2. Use children for generic wrappers
  3. Use named props for specific slots
  4. Keep layout components simple and presentational

Common Mistakes

  1. Nesting too many layers makes debugging hard
  2. Passing everything as children loses clarity
  3. Forgetting to spread props when needed