Astro: Astro components

In the previous lesson we’ve seen our first Astro site and I introduced components.

Let’s now talk more about them.

In their simplest form, components can just be some HTML tags, for example

<p>test</p>

Create a src/components/Test.astro file with that content, and import that in a page component, then add it to the component markup as you would write an HTML tag, like this

<Test />

See, the markup now appears in the page:

The syntax:

<Test />

was borrowed from JSX, a “templating language” introduced by React.

TIP: If you already know JSX, in Astro components the syntax is a little different, because for example we can have siblings in a tree (no need for fragment or <>) and no need to use className= to add HTML classes, just class=.

Components can add JavaScript variables in their “frontmatter”, and you can use them in the HTML markup:

---
const test = 'hello'
---

<p>{test}</p>

Let’s now talk about props.

Astro components accept props.

This means you can pass values to a component from a parent component.

For example we can pass a name attribute to the Test component like this:

<Test name="joe" />

Inside the Test component we can use this value by adding this to the component frontmatter:

---
const { name } = Astro.props
---

<p>test</p>

And now we can use it in the markup, using a special JSX-like syntax that lets us embed JavaScript inside the HTML:

---
const { name } = Astro.props
---

<p>test {name}</p>

Here’s the result:

And this is how we can embed data in Astro components.

If you had an array, you could print all items in the array using this syntax:

---
const list = [1, 2, 3, 4]
---

<p>Some numbers:</p>

<ul>
  {list.map(n => <li>{n}</li>)}
</ul>

Lessons in this unit:

0: Introduction
1: Your first Astro site
2: The structure of an Astro site
3: ▶︎ Astro components
4: Adding more pages
5: Dynamic routing
6: Markdown in Astro
7: Images
8: Content collections
9: CSS in Astro
10: JavaScript in Astro
11: Client-side routing and view transitions
12: SSR in Astro
13: API endpoints in Astro