BuildBot

Islands First

.astro components & props

Lesson 2 of 5

What you'll learn

  • Split an .astro file into frontmatter script and template
  • Understand the script runs once on the server at build time
  • Pass data into a component through Astro.props

An .astro file has two parts separated by a fence of three dashes. Above the fence is a frontmatter script — plain JavaScript or TypeScript that runs on the server at build time. Below it is the template, which looks like HTML with {} holes for values.

---
const { title, author } = Astro.props;
const year = new Date().getFullYear();
---
<article>
  <h1>{title}</h1>
  <p>by {author} — {year}</p>
</article>

The script never ships to the browser. By the time the page reaches a visitor, {title} has already been replaced with real text. This is why Astro pages are HTML-first: the dynamic work happened during the build.

Props flow in from the parent

A parent passes data as attributes; the child reads them from Astro.props.

---
import PostCard from "../components/PostCard.astro";
---
<PostCard title="Hello" author="Ada" />

Inside PostCard.astro, Astro.props is { title: "Hello", author: "Ada" }. Rendering is just interpolation: take props, fill the template's holes, emit a string of HTML.

Destructure at the top

Pull props out of Astro.props on the first line of the frontmatter. It documents the component's inputs in one place and gives you a natural spot to set defaults with =.

A component is a function from props to HTML. The challenge models that interpolation step directly.

Render a template from props

Run it. render() fills {key} placeholders in a template string with values from the props object — the core of how .astro turns props into HTML.

Loading editor…

Next: how to opt a component into shipping JavaScript.

Sign in to save your progress across devices.