Combining Variables and Inline Conditionals
What you'll learn: How to use extracted variables together with inline ternaries and && operators for clean, readable conditional rendering.
You don't have to choose between variables and inline conditionals — the best approach often uses both. Extract complex logic to variables before your return statement, then use simple ternaries or && operators in JSX for final presentation tweaks.
The Hybrid Approach
Think of it like cooking: you prep ingredients (variables) before plating, but you add the final garnish (inline conditional) right on the plate.
function UserGreeting({ user, isSubscribed }) {
// Extract complex logic to variables
const userName = user?.name || 'Guest';
const hasAccess = user && isSubscribed;
const showWarning = user && !isSubscribed;
return (
<div>
<h1>Welcome, {userName}!</h1>
{/* Simple inline conditional for final presentation */}
{hasAccess && <button>Access Premium Content</button>}
{showWarning ? (
<p className="warning">Subscribe to unlock features</p>
) : null}
{/* Variable + ternary combo */}
<span className={hasAccess ? 'badge-gold' : 'badge-silver'}>
{hasAccess ? 'Premium' : 'Free'}
</span>
</div>
);
}
The variables (userName, hasAccess, showWarning) handle the "what should I show?" logic. The inline conditionals handle the "how should I show it?" decisions — which component, which class name, which text.
This keeps your JSX readable while your logic remains testable and clear.
Key Takeaway: Extract complex boolean logic and data transformations to variables, then use inline && or ternaries in JSX only for simple presentation decisions — it's the sweet spot between clarity and conciseness.