Optional Slots with Conditional Rendering
What you'll learn: How to gracefully handle slots that might not receive content by conditionally rendering their containers.
The Problem with Always-Visible Slot Containers
When you define multiple slots in a component, you often wrap each slot in a container element for layout or styling purposes. But what happens when a parent doesn't provide content for a particular slot? You end up rendering empty containers that take up space or add unnecessary markup to the DOM.
Conditionally Rendering Slot Containers
The solution is to check whether a slot has content before rendering its container. Since slot props are just JSX elements (or undefined), you can use simple conditional logic:
function Card({ header, body, footer }) {
return (
<div className="card">
{header && (
<div className="card-header">
{header}
</div>
)}
<div className="card-body">
{body}
</div>
{footer && (
<div className="card-footer">
{footer}
</div>
)}
</div>
);
}
// Usage without optional slots
<Card body={<p>Only body content here</p>} />
// Renders no header or footer containers
Why This Matters
Without conditional rendering, empty <div className="card-header"></div> elements would appear in the DOM, potentially breaking your layout with unwanted spacing or borders. By checking {header && ...}, you ensure the container only exists when there's actual content to display.
Think of it like restaurant sections: you don't set up the dessert station if no one ordered dessert. Only prepare what's actually needed.
Key Takeaway: Always conditionally render slot containers using {slotName && <container>{slotName}</container>} to avoid empty markup and layout issues when slots aren't provided.