Astro cheatsheet
Astro: Components and layouts
6 common Astro tasks.
Component skeleton
An .astro file has JavaScript between the --- fences, which runs at build time, and a template below.
---
const title = "Hello, Astro";
const items = ["One", "Two", "Three"];
---
<h1>{title}</h1>
<ul>
{items.map((item) => <li>{item}</li>)}
</ul>
Accept props
Read props from Astro.props, with types.
---
interface Props {
title: string;
featured?: boolean;
}
const { title, featured = false } = Astro.props;
---
<article class:list={["card", { featured }]}>
<h2>{title}</h2>
</article>
Create a layout
A layout wraps pages and renders their content with <slot />.
---
const { title } = Astro.props;
---
<html lang="en">
<head><title>{title}</title></head>
<body>
<slot />
</body>
</html>
Use a layout in a page
Wrap page content in your layout component.
---
import Layout from "../layouts/Layout.astro";
---
<Layout title="Home">
<h1>Welcome</h1>
</Layout>
Optimize images
The Image component resizes, converts and lazy-loads images and sets width and height.
---
import { Image } from "astro:assets";
import hero from "../assets/hero.png";
---
<Image src={hero} alt="A mountain at sunrise" />
Style a component
Styles in a <style> tag apply only to that component.
<h1>Title</h1>
<style>
h1 { color: darkgreen; }
</style>