0
0
AstroHow-ToBeginner ยท 3 min read

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 if statements directly inside JSX is invalid; use ternary or logical operators instead.
  • Returning null or false will 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}