Default Slot Content
What you'll learn: How to provide fallback content when consumers don't pass anything to your component's slots.
The Problem with Empty Slots
When you create components with slots (content passed via props), sometimes consumers won't provide content for every slot. Without defaults, you'll get empty spaces or broken layouts. It's like a restaurant setting tables with empty placeholders — you need fallback options when guests don't order certain courses.
Providing Default Content
You can use the logical OR operator (||) or ternary operators to supply fallback content when a slot prop is undefined or null:
function Card({ header, footer }) {
return (
<div className="card">
<div className="card-header">
{header || <h2>Untitled Card</h2>}
</div>
<div className="card-footer">
{footer || <p>No additional information</p>}
</div>
</div>
);
}
// Using the default
<Card />
// Overriding the default
<Card
header={<h2>Custom Title</h2>}
footer={<button>Action</button>}
/>
Ternary for More Control
When you need different behavior based on whether content exists:
function Panel({ sidebar }) {
return (
<div className="panel">
<aside>
{sidebar ? sidebar : <nav>Default Navigation</nav>}
</aside>
</div>
);
}
Why This Matters
Defaults make your components resilient. They work immediately without forcing consumers to fill every slot, while still allowing complete customization when needed. Think of it as sensible defaults that can be overridden — the hallmark of flexible APIs.
Key Takeaway: Use logical OR (||) or ternary operators to provide default slot content, ensuring your components render gracefully even when consumers don't pass content to every slot.