How to Use Loops in Astro Template: Simple Guide
In Astro templates, use the
{items.map(item => ( ... ))} syntax to loop over arrays and render elements dynamically. This uses JavaScript's map function inside JSX-like braces to generate repeated content.Syntax
Astro templates use JavaScript expressions inside curly braces to loop over arrays. The common pattern is {array.map(item => ( ... ))}, where array is your list and item is each element.
Inside the parentheses, you return the JSX-like HTML you want repeated for each item.
astro
<ul>
<li>{array.map(item => (
<div>{item}</div>
))}</li>
</ul>Example
This example shows how to loop over a list of fruits and display each in a list item inside an unordered list.
astro
--- const fruits = ['Apple', 'Banana', 'Cherry']; --- <ul> {fruits.map(fruit => ( <li>{fruit}</li> ))} </ul>
Output
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
Common Pitfalls
One common mistake is forgetting to wrap the returned JSX in parentheses, which can cause syntax errors. Another is not using a unique key prop when rendering lists in React-based frameworks, but Astro does not require keys for static rendering.
Also, avoid using loops outside of curly braces; loops must be inside { } to be interpreted as JavaScript.
astro
--- const items = ['One', 'Two', 'Three']; --- <!-- Wrong: missing curly braces --> <ul> <li>items.map(item => <li>{item}</li>)</li> </ul> <!-- Right: use curly braces --> <ul> {items.map(item => ( <li>{item}</li> ))} </ul>
Quick Reference
- Use
{array.map(item => ( ... ))}to loop in Astro templates. - Wrap returned JSX in parentheses for clarity.
- Loops must be inside curly braces
{ }. - Astro supports JavaScript expressions directly in templates.
Key Takeaways
Use JavaScript's map function inside curly braces to loop in Astro templates.
Always wrap the returned JSX in parentheses for correct syntax.
Loops must be inside { } to be interpreted as JavaScript expressions.
Astro templates allow embedding JavaScript directly for dynamic rendering.
Avoid common mistakes like missing braces or parentheses around JSX.