Children and Conditional Rendering
You'll learn how to safely render children content only when it exists, avoiding errors from undefined or null children.
The Problem with Empty Children
Not every wrapper component always receives children. Sometimes a component might be used without any content between its tags, or the children might be conditionally passed. If you try to render or manipulate children without checking first, you might encounter unexpected behavior or errors.
function Card({ children }) {
// What if children is undefined or null?
return (
<div className="card">
{children}
</div>
);
}
// This works fine
<Card>
<p>Content here</p>
</Card>
// But what about this?
<Card />
Checking Before Rendering
The good news: JSX safely renders null and undefined as nothing. But you often want to conditionally show wrapper elements or default content only when children exist (or don't exist):
function Card({ children }) {
if (!children) {
return <div className="card empty">No content provided</div>;
}
return (
<div className="card">
<div className="card-header">Content:</div>
{children}
</div>
);
}
Or using inline conditional rendering:
function Card({ children }) {
return (
<div className="card">
{children && <div className="card-header">Content:</div>}
{children}
{!children && <p className="empty">Nothing to display</p>}
</div>
);
}
This pattern ensures you only render related elements (like headers or borders) when there's actual content to display, and can provide helpful fallbacks when children are absent.
Key Takeaway: Always consider that children might be undefined or null—use conditional rendering to handle empty cases gracefully and show appropriate fallback content or structure.