Flexible Layouts: Slot Pattern in React

Use children to define placeholders (slots) for flexible UI composition. Cards, modals, and dashboards benefit from this approach. Avoid when it confuses API users or complicates layouts.

The Slot Pattern allows a parent component to define placeholder areas (slots) where consumers can inject custom components or content.

👉 Think of it like a theater stage with empty slots — the stage is ready, but the actors (children) decide what appears in each slot.

Basics & Need

  • Useful when building highly reusable components with customizable sections.
  • Consumers can provide arbitrary content without the parent knowing exact implementation details.
  • Often used in component libraries for UI elements like modals, cards, tabs, and forms.

How to Achieve It

Example 1: Named Slots via Props

const Card = ({ header, body, footer }) => {
return (
<div className="card">
<div className="card-header">{header}</div>
<div className="card-body">{body}</div>
<div className="card-footer">{footer}</div>
</div>
);
};

// Usage
<Card
header={<h2>Title</h2>}
body={<p>This is the content</p>}
footer={<button>Click Me</button>}
/>

👉 Each slot (header, body, footer) is injected by the consumer.


Example 2: Children as Function (Dynamic Slot)

const List = ({ items, children }) => (
<ul>
{items.map((item, idx) => (
<li key={idx}>{children(item)}</li>
))}
</ul>
);

// Usage
<List items={["React", "Vue", "Angular"]}>
{(item) => <strong>{item}</strong>}
</List>

👉 Consumer controls rendering of each item, giving dynamic flexibility.

Best Practices

  • Name slots clearly when using multiple props (header, body, footer).
  • For complex dynamic content, use children as function for flexibility.
  • Combine with compound components for reusable patterns.
  • Document the slots and expected usage for consumers.

Real-World Examples

  1. Modal Componentheader, body, footer slots for custom content.
  2. Tabs / Accordion → Consumer provides content for each tab panel.
  3. Form Library → Slots for custom input, buttons, or validation messages.

Advantages

  • Highly flexible and reusable components.
  • Allows consumers to inject custom content easily.
  • Keeps component logic separate from content.
  • Works seamlessly with compound components.

Disadvantages

  • Can increase complexity if too many slots are exposed.
  • Requires clear documentation to avoid misuse.
  • Overuse may make component hard to read or debug.

Common Problems / Pitfalls

  • Forgetting to handle empty slots → may break layout.
  • Overcomplicating slot names or API → consumers confused.
  • Not handling dynamic content correctly → runtime errors.

Summary Recommendation

Use the Slot Pattern when you want a component to accept arbitrary content in defined placeholders. Perfect for modals, cards, forms, and dynamic lists. Combine with compound components or render props for maximum flexibility and maintainable UI libraries.