How to Use Conditional Rendering in Astro: Simple Guide
In Astro, use JavaScript expressions inside
{ } to conditionally render content. You can use ternary operators or logical && inside JSX-like syntax to show or hide elements based on conditions.Syntax
Astro uses JSX-like syntax for rendering. You place JavaScript expressions inside { }. For conditional rendering, use a ternary operator condition ? trueContent : falseContent or logical AND condition && content.
This lets you decide what to show based on a condition.
astro
<!-- Ternary operator example -->
{isLoggedIn ? <p>Welcome back!</p> : <p>Please log in.</p>}
<!-- Logical AND example -->
{showMessage && <p>This message shows only if showMessage is true.</p>}Example
This example shows a simple Astro component that displays a greeting if isLoggedIn is true, otherwise it asks the user to log in.
astro
--- const isLoggedIn = true; --- <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Conditional Rendering Example</title> </head> <body> <main> {isLoggedIn ? <h1>Welcome back, user!</h1> : <h1>Please log in to continue.</h1>} </main> </body> </html>
Output
<h1>Welcome back, user!</h1>
Common Pitfalls
- Forgetting to wrap JavaScript expressions in
{ }causes syntax errors. - Using
ifstatements directly inside JSX is invalid; use ternary or logical operators instead. - Returning
nullorfalsewill render nothing, which is useful to hide elements.
astro
<!-- Wrong: if statement inside JSX --> {/* {if (isLoggedIn) { <p>Welcome!</p> }} */} <!-- Right: use ternary --> {isLoggedIn ? <p>Welcome!</p> : null}
Quick Reference
Key Takeaways
Use JavaScript expressions inside { } for conditional rendering in Astro.
Prefer ternary operators or logical && for showing or hiding elements.
Never use if statements directly inside JSX; they cause errors.
Returning null or false hides elements cleanly.
Always wrap your conditions and content inside { } in Astro templates.