Using if/else Before Return
You'll learn how to handle complex conditional rendering by placing standard if/else statements before your return, making your JSX cleaner and easier to read.
When Inline Conditionals Aren't Enough
When your conditional logic gets complicated—multiple branches, nested conditions, or decisions that affect large chunks of JSX—squeezing everything into inline ternaries or && operators makes your code hard to follow. The solution? Move the logic above the return statement using regular JavaScript if/else blocks.
The Pattern: Decide First, Render Second
Instead of cramming logic into your JSX, you make decisions beforehand and either:
- Return early from different branches
- Assign JSX to a variable, then render that variable
Early return example:
function Greeting() {
const hour = new Date().getHours();
if (hour < 12) {
return <h1>Good morning!</h1>;
} else if (hour < 18) {
return <h1>Good afternoon!</h1>;
} else {
return <h1>Good evening!</h1>;
}
}
Variable assignment example:
function StatusBadge() {
const status = "pending";
let badge;
if (status === "approved") {
badge = <span>✓ Approved</span>;
} else if (status === "pending") {
badge = <span>⏳ Pending</span>;
} else {
badge = <span>✗ Rejected</span>;
}
return <div>{badge}</div>;
}
Why This Works Better
Think of it like planning an outfit before you leave the house instead of changing clothes in the hallway. You've made all your decisions before the critical moment. Your return statement stays focused on structure, not logic.
Key Takeaway: When conditions become complex, use standard if/else blocks before your return statement—either returning early from each branch or assigning JSX to a variable you render later.