Optional Slots with Conditional Rendering
What you'll learn: How to gracefully handle slots that might not be provided, using conditional rendering to show fallback content or skip wrapper elements entirely.
The Core Idea
Not every slot needs to be filled every time. When a component offers multiple slots (like header, footer, sidebar), consumers might only provide some of them. Your component should handle missing slots elegantly — either by rendering fallback content, skipping unnecessary wrapper elements, or adapting the layout dynamically.
Think of it like a restaurant booth: if there's no one sitting on one side, you don't need to set that place with silverware and napkins. Your component should be equally flexible.
Implementing Optional Slots
The key is checking whether a slot prop exists before rendering it or its wrapper:
function Card({ header, content, footer }) {
return (
<div className="card">
{header && (
<div className="card-header">
{header}
</div>
)}
<div className="card-content">
{content}
</div>
{footer && (
<div className="card-footer">
{footer}
</div>
)}
</div>
);
}
Notice how the header and footer wrappers only render when those props are provided. This prevents empty <div> elements from cluttering your DOM and affecting CSS layouts.
When to Use This Pattern
- Flexible layouts: Components that adapt to available content
- Wrapper elimination: Avoid rendering containers for empty slots
- CSS-sensitive designs: Layouts that break with empty elements
- Performance: Skip rendering unnecessary DOM nodes
Key Takeaway: Use conditional rendering (&&) to check if slot props exist before rendering them or their wrapper elements, keeping your DOM clean and your layouts flexible.