Extracting Ternaries to Variables for Clarity
What you'll learn: How to keep your JSX clean and readable by moving complex ternary expressions into variables before your return statement.
Why Extract Ternaries?
When ternaries get long or complex, they can make your JSX hard to scan. Instead of cramming everything inline, you can assign the ternary's result to a const variable before the return. This keeps your JSX focused on structure, while the logic lives in named variables that explain what you're rendering.
Think of it like meal prep: instead of chopping vegetables while assembling a sandwich, you prep everything first, then assemble. The sandwich-making becomes simpler and faster.
The Pattern
function StatusMessage({ isLoggedIn, userName }) {
// Extract the ternary to a descriptive variable
const greeting = isLoggedIn
? `Welcome back, ${userName}!`
: 'Please log in';
return (
<div>
<h1>{greeting}</h1>
</div>
);
}
Notice how greeting has a clear name and the JSX just uses {greeting}. No mental parsing needed.
Multiple Extractions
You can extract several decisions:
function ProductCard({ inStock, price }) {
const stockMessage = inStock ? 'Available' : 'Sold Out';
const priceDisplay = inStock ? `$${price}` : null;
return (
<div>
<p>{stockMessage}</p>
{priceDisplay}
</div>
);
}
Benefits
- Readability: Named variables act as inline documentation
- Testability: You could even unit-test that variable logic separately if extracted to a helper
- Debugging: Easier to console.log a variable than an inline expression
Key Takeaway: Assign complex ternary results to const variables before return to keep JSX readable and maintainable—your teammates (and future you) will thank you.