How to create For loops in Astro components

Jamie Carter
6 min readFeb 4, 2024

--

Let’s dive into the world of For loops and repeating HTML elements in Astro components.

While setting up my first project using Astro I hit a bump in the road…

How do I create repeating HTML elements in an Astro component?

I migrated from VueJS to try AstroJS after reading all the hype online about but soon realised the syntax to write Astro components was radically different to Vue.

In case you were unsure about how to google astro syntax in future it is similar to React and Solidjs, more specifically jsx and tsx syntax.

Now you better understand what to look for, let’s get started.

Basic loops

In Astro we mix JS expression with HTML directly in the component.

The important thing to learn here is that instead of reaching for a for-loop in astro, as we might in other frameworks, we need to use an Array.map() function.

Let’s look at an example of printing out the names of our favourite cities from a list:

---
const myFavouriteCities = [
{
name: "london",
country: "england"
},
{
name: "barcelona",
country: "spain"
}
]
---

<ul>
{
myFavouriteCities.map((data) => <li>{data.name}</li>)
}
</ul>

--

--

Jamie Carter

Product designer, frontend developer and pharmacist. Passionate about Design, UX, CSS (Tailwind), DataVis and AstroJS. Twitter: @jamiecarter7. Work: simple.org