Components and layouts

Import and compose components

Build pages from small components without turning every HTML element into an abstraction.

8 minute lesson

~~~

Import a component in frontmatter, then use its capitalized name in the template:

---
import Card from "../components/Card.astro"
---

<section class="cards">
  <Card title="HTML first" />
  <Card title="JavaScript when needed" />
</section>

Astro resolves the import while rendering. Each <Card> produces ordinary HTML; the browser does not download a component runtime or fetch Card.astro.

Components are useful boundaries for repeated UI, a distinct responsibility, or a piece with its own styles and data. A Header, ProductCard, or NewsletterForm usually earns a component. A one-off paragraph usually does not.

Composition also makes data flow visible. The page chooses which cards exist and passes their values. The card owns how one item is presented. Neither needs to know the other’s whole implementation.

After extracting a component, inspect the generated HTML. If the output becomes needlessly nested or the reader must jump between several files to understand simple markup, the abstraction is costing more than it saves. Astro makes components cheap at runtime, but they still have a maintenance cost for humans.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →