Performance: Component expressions and conditionals
This affects how quickly the page renders by controlling which components and elements are included in the DOM and how often the browser recalculates layout.
<Component>{condition && <HeavyComponent />}</Component><Component>{condition ? <HeavyComponent /> : <AnotherHeavyComponent />}</Component>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Complex nested conditionals rendering many components | High number of nodes created | Multiple reflows triggered | High paint cost due to many elements | [X] Bad |
| Simple conditional rendering only needed components | Minimal nodes created | Single reflow | Low paint cost | [OK] Good |
{condition && <Component />} do?{condition && <Component />} uses JavaScript's logical AND. It returns the component only if condition is true.condition is false, the whole expression returns false, so nothing renders.condition ? exprIfTrue : exprIfFalse syntax, which works inside Astro expressions.{condition ? <A /> : <B />} matches the correct ternary syntax. Other options use invalid keywords like if/else or then, or miss the colon separator.{isLoggedIn ? Welcome back!
: Please log in.
}isLoggedIn is false?isLoggedIn is false.isLoggedIn is false, the expression returns the part after the colon: <p>Please log in.</p>.{user.isAdmin ? <AdminPanel />}{user.isAdmin ? <AdminPanel />} attempts a ternary operator but lacks the required : and else part, causing a syntax error.condition ? trueExpr : falseExpr. Missing parts cause parse errors; use && for optional render instead.user.isAdmin is false, but no error occurs. -> Option Cname is a non-empty string, otherwise show "Hello, guest!". Which expression correctly does this?name is truthy (non-empty string) to show personalized greeting.{name ? Hello, {name}!
: Hello, guest!
} uses ternary correctly: if name is truthy, show "Hello, {name}!" else "Hello, guest!". {name && Hello, {name}!
|| Hello, guest!
} mixes && and || incorrectly. {name ? Hello, guest!
: Hello, {name}!
} reverses greetings. {name && Hello, guest!
? Hello, {name}!
: null} has invalid syntax mixing && and ternary.Pass the test and this pattern moves unknown