astrojs

Looping through an array in an AstroJS component


I try to loop an array in an Astro.js component, but it doesn't return anything: In my example, I replaced the cards const from Astro.props with a hardcoded one for readability. I don't get anything from the forEach loop, but the Card component at the end is displayed correctly.

If I replace the Card component in the loop with a basic one like div (empty div), it still doesn't work, but if I replace it with a console.log(card), I do have the printed output in the terminal, so the loop works.

I can provide the Card.astro file if needed, but I don't think it's relevant here.

  ---
    import Card from './Card.astro';
    import type { Props as CardProps } from './Card.astro';

type Props = { cards: CardProps[] };

// const { cards } = Astro.props;
const cards = [
  {
    gradientFrom: '#125245',
    gradientTo: '#fe1548',
    title: 'Boo',
    to: '/link1',
  },
  {
    gradientFrom: '#125245',
    gradientTo: '#fe1548',
    title: 'second card',
    to: '/link2',
  },
];
---

<div class="cards">
  {
    cards.forEach((card) => (
      <Card
        gradientFrom={card.gradientFrom}
        gradientTo={card.gradientTo}
        to={card.to}
        title={card.title}
      />
    ))
  }
  <Card
    gradientFrom={cards[0].gradientFrom}
    gradientTo={cards[0].gradientTo}
    to={cards[0].to}
    title={cards[0].title}
  />
</div>

Solution

  • forEach method doesnt return anything. Can you change forEach to map function ?

    <div class="cards">
      {
        cards.map((card) => (
          <Card
            gradientFrom={card.gradientFrom}
            gradientTo={card.gradientTo}
            to={card.to}
            title={card.title}
          />
        ))
      }
      <Card
        gradientFrom={cards[0].gradientFrom}
        gradientTo={cards[0].gradientTo}
        to={cards[0].to}
        title={cards[0].title}
      />
    </div>