#How to render mdx from a frontmatter field

4 messages · Page 1 of 1 (latest)

red jungle
#

How to render mdx from a frontmatter field that contains Astro components like:

---
title: My title
intro: |
  ## Some heading
  
  Some paragraph
  
  <SomeComponent/>
---
marble lightBOT
#

Hi @red jungle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Astro supports using frontmatter in MDX files by default. You can add frontmatter properties just as you would in Markdown files, and these variables are available to use in the template, and as named properties when importing the file somewhere else. However, the frontmatter field is typically used for metadata and not for rendering components or MDX content.

If you want to render MDX content, you would typically do this outside of the frontmatter section. For example:

---
layout: '../../layouts/BlogPostLayout.astro'
title: 'My first MDX post'
---
# {frontmatter.title}

## Some heading
Some paragraph
<SomeComponent/>

In this example, SomeComponent would need to be an Astro or UI framework component that you've imported into your MDX file. For example:

---
layout: '../../layouts/BlogPostLayout.astro'
title: 'My first MDX post'
---
import SomeComponent from '../components/SomeComponent.astro';

# {frontmatter.title}

## Some heading
Some paragraph
<SomeComponent/>

If you want to pass frontmatter and headings props directly to a specified layout component, you can use the special Markdown layout property in the frontmatter of MDX files. For example:

---
layout: '../../layouts/BaseLayout.astro'
title: 'My first MDX post'
publishDate: '21 September 2022'
---
import BaseLayout from '../../layouts/BaseLayout.astro';

<BaseLayout title={frontmatter.title}>  
  Welcome to my new Astro blog, using MDX!
</BaseLayout>

In this case, your values are available to you through Astro.props in your layout, and your MDX content will be injected into the page where your <slot /> component is written.