Multiple Slot Example: Card Component
You'll learn how to build a flexible Card component with multiple named slots for header, body, and footer content.
The Card Component Pattern
A Card is the perfect example for demonstrating multiple slots because it naturally divides into distinct content areas. Instead of cramming everything into children, you expose separate props for each section, giving consumers precise control over layout and composition.
Think of it like a picture frame with labeled compartments: one slot for the title at the top, one for the main content in the middle, and one for action buttons at the bottom. Each compartment accepts different content, but the frame (Card) handles the spacing, borders, and overall structure.
Building a Multi-Slot Card
interface CardProps {
header?: React.ReactNode;
body: React.ReactNode;
footer?: React.ReactNode;
variant?: 'default' | 'outlined';
}
function Card({ header, body, footer, variant = 'default' }: CardProps) {
return (
<div className={`card card--${variant}`}>
{header && (
<div className="card__header">
{header}
</div>
)}
<div className="card__body">
{body}
</div>
{footer && (
<div className="card__footer">
{footer}
</div>
)}
</div>
);
}
// Usage
<Card
header={<h2>Product Title</h2>}
body={<p>Product description goes here...</p>}
footer={<button>Add to Cart</button>}
/>
Notice how the Card component controls the structure (wrapping divs, conditional rendering) while the consumer provides the actual content. Header and footer are optional, but body is required—reflecting typical card usage patterns.
Key Takeaway: The multi-slot pattern shines when a component has distinct, named content areas with different layout purposes—use props to expose each slot clearly rather than relying on a single children prop.