Learn Astro · 3/15

Mastering .astro Components

7 min read

Course: Astro

Topic: Mastering .astro Components


Introduction

Welcome to the heart of Astro. If pages are the map of your application, Components are the bricks, mortar, and steel beams that construct the scenery.

In the previous modules, you set up the environment and understood the file structure. Now, we move to the core file extension: .astro. Unlike React's JSX or Vue's SFCs, Astro components are HTML-only templating languages with zero client-side JavaScript overhead by default. They represent a return to the simplicity of HTML, supercharged with the power of server-side JavaScript.

This guide explores the anatomy of an Astro component, how to make them dynamic with Props, how to compose them with Slots, and how to control their rendering with Directives.


1. The Component Script vs. Component Template

An .astro file is separated into two distinct parts. This separation is visual and functional, demarcated by a "code fence" (three dashes).

Definition

An Astro component consists of:

  1. The Component Script (Frontmatter): The code between the --- fences. This is JavaScript (or TypeScript) that runs only during the build process (or on the server during SSR).
  2. The Component Template: The HTML-like syntax below the fence.

The Problem

In traditional HTML, you cannot calculate variables or fetch data. You have to write static text. In early Single Page Application (SPA) frameworks, you often mixed logic and UI so tightly that performance suffered due to heavy JavaScript bundles sent to the browser.

The Solution

Astro separates the logic (Script) from the view (Template). The logic runs entirely on the server/build machine. The browser receives only the resulting HTML.

The Syntax:

astro
---
// 1. Component Script (Server-side JS/TS)
// This code runs at build time!
const pageTitle = "Hello World";
const currentYear = new Date().getFullYear();

// You can even fetch data here
const response = await fetch('https://api.example.com/data');
const data = await response.json();
---

<!-- 2. Component Template (HTML + JS Expressions) -->
<div class="container">
  <h1>{pageTitle}</h1>
  <p>Copyright {currentYear}</p>
  
  <!-- Render fetched data -->
  <ul>
    {data.items.map((item) => (
      <li>{item.name}</li>
    ))}
  </ul>
</div>

Key Concept: The Exclusion Principle
Variables defined in the Component Script are available in the Template. However, variables defined in the Script are never sent to the client browser unless you explicitly use them in a <script> tag within the HTML. This ensures your secrets and build-logic stay on the server.

💡 Fun Fact: The "Code Fence" syntax (---) was popularized by Markdown frontmatter (used in Jekyll and Hugo). Astro borrowed this to make static site developers feel right at home. It’s like a cozy blanket for your code.


2. Passing Data Downward with Props 🎁

Components are useless if they always render the same text. To make them reusable, we need to pass data into them.

Definition

Props (short for properties) are inputs you pass to a component, similar to attributes on an HTML element (like src in an <img> tag).

The Problem

Imagine you are building a "Product Card". Without props, you would need to create ProductCard1.astro, ProductCard2.astro, and ProductCard3.astro, copying the HTML every time just to change the title and price. This violates the DRY (Don't Repeat Yourself) principle.

The Solution

Astro exposes a global object called Astro.props. You can access attributes passed to the component through this object.

Step 1: The Child Component (Card.astro)

astro
---
// Access values passed from the parent
const { title, description, price = 0 } = Astro.props;
---

<div class="card">
  <h2>{title}</h2>
  <p>{description}</p>
  <!-- Format price simply -->
  <span>Price: ${price.toFixed(2)}</span>
</div>

Step 2: The Parent Component (index.astro)

astro
---
import Card from '../components/Card.astro';
---

<main>
  <Card 
    title="Ergonomic Chair" 
    description="Sit comfortably for hours." 
    price={299} 
  />
  
  <Card 
    title="Wooden Desk" 
    description="Oak finish, sturdy build." 
    price={150} 
  />
</main>

Industry Standard: TypeScript Interfaces

In professional environments, we do not guess what props are available. We define them strictly using TypeScript. This provides autocomplete and error checking in your editor.

astro
---
// Define the shape of the data
interface Props {
  title: string;
  description: string;
  price?: number; // Optional prop
  isInStock?: boolean;
}

const { title, description, price = 0, isInStock = true } = Astro.props;
---

<div class={isInStock ? "product" : "product out-of-stock"}>
  <h2>{title}</h2>
  <!-- UI Logic -->
</div>

3. Slots: Building Reusable Wrappers and Layouts

Props are excellent for strings, numbers, and objects. But what if you want to pass a chunk of HTML, a button, or another component inside a component?

Definition

The <slot /> element is a placeholder for external HTML content. It allows a parent component to inject children into a specific spot within a child component.

The Problem

You want to create a standard "Page Layout" with a Navbar and Footer, where the content changes on every page. Passing the entire page content as a string prop (e.g., content="<h1>Home</h1>...") is unreadable, unsafe, and impractical.

The Solution

Astro uses the HTML <slot> element.

Basic Slot Example (MainLayout.astro):

astro
---
// MainLayout.astro
---
<html>
  <body>
    <nav>My Website</nav>
    
    <main>
      <!-- The content from the parent will appear here -->
      <slot /> 
    </main>
    
    <footer>© 2026</footer>
  </body>
</html>

Usage (index.astro):

astro
---
import MainLayout from '../layouts/MainLayout.astro';
---

<MainLayout>
  <!-- Everything here is injected into the <slot /> -->
  <h1>Welcome Home</h1>
  <p>This is the main content.</p>
</MainLayout>

Advanced: Named Slots

Sometimes a layout needs multiple injection points (e.g., a header section and a sidebar). You can name your slots.

The Child (Panel.astro):

astro
<div class="panel">
  <div class="panel-header">
    <slot name="header" />
  </div>
  <div class="panel-body">
    <slot /> <!-- Default slot -->
  </div>
</div>

The Parent usage:

astro
<Panel>
  <h3 slot="header">Settings</h3> <!-- Goes to 'header' slot -->
  <p>Here you can change your preferences.</p> <!-- Goes to default slot -->
</Panel>

🧪 Fallback Content: You can put content inside the <slot>Default Text</slot> tags. If the parent doesn't provide content, the "Default Text" will render. This is excellent for defensive design.


4. Understanding Fragments and HTML Directives

Sometimes standard HTML isn't enough. You might need to render a list of classes conditionally or output raw HTML strings.

Fragments (<Fragment />)

The Problem: HTML structure usually requires a single parent element. If you return two <div>s side-by-side without a wrapper, HTML parsers may get confused, or you might break your CSS grid by adding an unnecessary wrapper div.

The Solution: Astro supports Fragments. These are invisible wrappers that disappear in the final DOM.

astro
---
const items = ['Apple', 'Banana', 'Cherry'];
---

<!-- Short syntax for Fragment -->
<>
  {items.map((item) => (
    <li>{item}</li>
  ))}
</>

HTML Directives

Directives are special attributes that control how an element behaves. They are prefixed with client:, set:, or class:.

1. class:list (The Utility Warrior)
Dynamically constructing a string of class names is tedious: class={`btn ${active ? 'active' : ''} ${large ? 'lg' : ''}`}. This is hard to read.

Astro provides class:list, which accepts an array or object.

astro
---
const { isError, isLarge } = Astro.props;
---

<!-- If isError is true, 'error' class is added. 'btn' is always added. -->
<button class:list={[ 'btn', { error: isError, large: isLarge } ]}>
  Click Me
</button>

2. set:html (The CMS Connector)
By default, Astro escapes HTML content to prevent XSS (Cross-Site Scripting) attacks. If you render <p>{content}</p> and content contains <strong>Hi</strong>, the user will literally see the tags.

If you trust the source (e.g., your own CMS), use set:html.

astro
---
const cmsContent = "<strong>Bold move!</strong>";
---

<div set:html={cmsContent} />

⚠️ Warning: Never use set:html with user-generated content (like comments) without sanitizing it first. It creates an open door for hackers to inject malicious scripts.


Summary Checklist

  1. Code Fences (---): Logic goes here. Runs on the server.
  2. Props: Use Astro.props and TypeScript interfaces to pass data safely.
  3. Slots: Use <slot /> for layouts and nesting HTML. Use Named Slots for complex components.
  4. Directives: Use class:list for clean CSS logic and set:html for raw content.

You have now moved beyond simple HTML pages. You are thinking in Components: reusable, strictly typed, and composable units of UI.


📚 References & Further Reading

Challenge

Challenge Instructions

Your task is to build a reusable blog post layout system using Astro components, props, slots, and directives. You will create two interconnected components within a single file context, as if you were creating src/layouts/BlogPostLayout.astro and src/pages/index.astro.

Part 1: Create the BlogPostLayout.astro Component

First, define the layout component. This component will be responsible for the overall structure of a blog post page.

  1. Define Props: Inside the component script (the top code fence ---), define a TypeScript interface named Props. This interface must specify the following properties and their types:
    • title: string
    • author: string
    • publishDate: Date
    • isFeatured: boolean
    • shareWidgetHTML: string (This will contain raw HTML)
  2. Access Props: Use Astro.props to access the props passed to the component.
  3. Component Template: Create the HTML structure for the layout below the code fence.
    • The root element should be an <article>.
    • Use the class:list directive on the <article> element to conditionally apply a featured-post class only when the isFeatured prop is true.
    • Inside the <article>, create a <header> section. It should contain:
      • A named slot for a header image: <slot name="header-image" />.
      • An <h1> that displays the title prop.
      • A <p> tag that displays the author and the formatted publishDate (use publishDate.toDateString()).
    • Below the <header>, add a default <slot /> to act as a placeholder for the main blog content.
    • Create a <footer> section. It should contain:
      • A named slot for an author biography: <slot name="author-bio" />. This slot must have fallback content: a <p> tag with the text Author biography not provided..
      • Use the set:html directive to render the raw HTML from the shareWidgetHTML prop.

Part 2: Create the index.astro Page

Next, create the page that will use your BlogPostLayout component to display a specific post.

  1. Import Layout: In the script section for this page, import the BlogPostLayout component you just defined.
  2. Define Post Data: Create the necessary variables to pass as props to the layout component. Set isFeatured to true and for shareWidgetHTML, use the string '<div class="share-links"><a href="#">Share</a></div>'.
  3. Use Layout: In the template section, use the <BlogPostLayout> component and pass all the required props.
  4. Populate Slots:
    • Provide content for the header-image slot by adding an <img> tag with the attribute slot="header-image". Use any placeholder URL for the src.
    • Provide content for the default slot by placing at least one <p> tag with some sample blog text directly inside the <BlogPostLayout> component tags.
    • Crucially, do not provide any content for the author-bio slot, so that its fallback content will be rendered.

Expected result

Your final code should consist of two complete Astro components. The first is a flexible layout that uses props for data, named slots for customizable sections, a default slot for primary content, and directives for dynamic classes and HTML rendering. The second component is a page that consumes this layout, passing data and injecting content into the appropriate slots.

Correct BlogPostLayout.astro implementation:

astro
---
interface Props {
  title: string;
  author: string;
  publishDate: Date;
  isFeatured: boolean;
  shareWidgetHTML: string;
}

const { title, author, publishDate, isFeatured, shareWidgetHTML } = Astro.props;
---
<article class:list={[{ 'featured-post': isFeatured }]}>
  <header>
    <slot name="header-image" />
    <h1>{title}</h1>
    <p>By {author} on {publishDate.toDateString()}</p>
  </header>

  <slot />

  <footer>
    <slot name="author-bio">
      <p>Author biography not provided.</p>
    </slot>
    <Fragment set:html={shareWidgetHTML} />
  </footer>
</article>

Correct index.astro implementation:

astro
---
import BlogPostLayout from '../layouts/BlogPostLayout.astro';

const postData = {
  title: "Mastering Astro Components",
  author: "Astro Developer",
  publishDate: new Date(),
  isFeatured: true,
  shareWidgetHTML: '<div class="share-links"><a href="#">Share</a></div>'
};
---
<BlogPostLayout {...postData}>
  <img slot="header-image" src="/placeholder.jpg" alt="Astro logo banner" />
  <p>This is the main content of our blog post, rendered inside the default slot.</p>
  <p>Slots and props make Astro components incredibly reusable and powerful.</p>
</BlogPostLayout>
astro

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.