Hey there, Fellow Coder! đź‘‹
Ever found yourself staring at a component that looks like a bowl of spaghetti because of all the if-else blocks? Or maybe you’ve created a monster with nested ternary operators that requires a PhD to decode?
We’ve all been there.
Today, we’re going to talk about Conditional Rendering. It’s a fancy term for “Showing different things based on the situation.”
Let’s look at 4 patterns to keep your React code clean and readable. 🧹
1. The Classic if Statement
Sometimes, the old ways are the best ways. If you want to stop a component from rendering entirely, or handle a loading state early, the good old if is your best friend.
The “Early Return” Pattern:
const UserProfile = ({ user, isLoading }) => {
// Pattern: Early Return
if (isLoading) {
return <div>Loading...</div>;
}
if (!user) {
return <div>Please log in.</div>;
}
return (
<div>
<h1>Welcome, {user.name}!</h1>
</div>
);
};
This is super clean. You handle the edge cases first, and the rest of your component logic stays simple.
2. The Ternary Operator ? :
This is the bread and butter of React conditionals. It’s great for binary choices: “If this is true, show A, otherwise show B.”
const LoginButton = ({ isLoggedIn }) => {
return (
<button>
{isLoggedIn ? "Logout" : "Login"}
</button>
);
};
Pro Tip: Don’t nest these! If you find yourself writing condition ? (subCondition ? A : B) : C, please stop. Your future self will thank you.
3. The Logical AND &&
Use this when you want to render something only if a condition is true, and render nothing otherwise.
const Notification = ({ hasError }) => {
return (
<div>
{hasError && <p className="text-red-500">Something went wrong!</p>}
</div>
);
};
⚠️ Warning: The “Zero” Trap
Be careful with numbers! In JavaScript, 0 is falsy, but React renders it as the number 0.
// ❌ If count is 0, this renders "0" on the screen!
{count && <h1>Messages: {count}</h1>}
// âś… Fix: Make it a boolean
{count > 0 && <h1>Messages: {count}</h1>}
4. Object/Enum Mapping (The Pro Move) đź§
What if you have multiple conditions? Like rendering a different status badge for “Active”, “Inactive”, “Pending”, and “Banned”?
Using if-else or switch inside JSX is messy. Using nested ternaries is a crime.
Instead, use an object mapping!
const StatusBadge = ({ status }) => {
// Define the map
const statusColors = {
active: "bg-green-500",
inactive: "bg-gray-500",
pending: "bg-yellow-500",
banned: "bg-red-500",
};
// Select the color, fallback to gray if unknown
const colorClass = statusColors[status] || "bg-gray-500";
return <span className={`p-2 rounded ${colorClass}`}>{status}</span>;
};
This is declarative, easy to read, and easy to extend. Just add a new key-value pair!
Closing Thoughts
Conditional rendering doesn’t have to be complicated.
- Use
iffor early returns. - Use
ternaryfor A vs B. - Use
&&for “Show or Hide”. - Use Object Mapping for multiple options.
Keep it simple, keep it clean.
Happy Coding! 🚀