javascriptastrojsstatic-site-generation

How to render multiple Markdown files on one page in Astro?


I want to render the contents of multiple .md files on a single page using Astro.

I have this file structure:

pages/
  items/
    item-1.md
    item-2.md
    item-3.md
    // etc
  index.astro

item-1.md looks like this:

---
title = 'Item 1'
---

Item 1 main text

And in index.astro:

---
const items = await Astro.glob([
    './items/*.md',
]);
---

<html lang="en">
    <body>
        {items.map((item) =>
            item.Content
        )}
    </body>
</html>

What I get as a result is:

[object Object][object Object][object Object]

Instead of the expected:

Item 1 main text
Item 2 main text
Item 3 main text

How can I make it so that the output HTML calculated from Markdown appears on the page?


Solution

  • item.Content is an Astro component, so in your index.astro file you will need to render it like this:

    ---
    const items = await Astro.glob('./items/*.md');
    ---
    
    <html lang="en">
        <body>
            {items.map((item) =>
                <item.Content />
            )}
        </body>
    </html>
    

    You could also destructure it in the map, but these are functionally equivalent:

            {items.map(({ Content }) =>
                <Content />
            )}