Markdown Extended, mdx for short, is a combination between Markdown and JSX. The best feature of MDX is it lets you use components in Markdown.
You can import and use any component directly — just like if you’re using them in Astro. Here’s an example where I use the Demo component right in this lesson’s mdx file.
---# Frontmatter---import Demo from '../components/Demo.svelte'
<Demo> ## This is a component
Pretty nice, eh?</Demo>This is a component
Pretty nice, eh?Installing MDX
Astro folks have built an integration for MDX so it’s easy-peasy to add it to your project. Just follow these instructions.
Basically, run this and you’re done.
npx astro add mdxWays to use MDX
The same three ways to use Markdown work with MDX as well.
- Direct import
- Content collections
- Markdown layout
This brings us to the first way.
Direct Imports
Both md and mdx files can be imported directly into an Astro file.
---import MDContent from '../<path>/file.md'import MDXContent from '../<path>/file.mdx'---
<MDContent /><MDXContent />You can also import mdx components into mdx files too — this process is the same as importing a framework component into mdx.
---# Frontmatter---
import MDXContent from '../path/file.mdx'
<MDXContent />This is the simplest way to use md and mdx files, but I rarely use md or mdx this way. I typically use them via other methods.
Passing components into MDX
You can pass components into your MDX files so they do not have to import them themselves. This is very useful if you’re using them with content collections.
Here’s an example where I passed the Image and Video components from Splendid Labz into an MDX component.
---import MDXContent from '../path/file.mdx'import {Image, Video} from '@splendidlabz/astro'const components = { Image, Video}---
<MDXContent {components} />Once that’s done, I can use Image and Video directly without further imports.
---# Frontmatter---
<Image ... /><Video ... />Now, before we go into the next method, content collections, let me tell you about an awesome feature that I’ve built — a Markdown component.
Astro v6 bug
Astro has a bug in version 6 with its integration with MDX — when you update an MDX file, the browser does not refresh automatically.
This makes in an incredibly frustrating experience working with MDX.
The good news is, this bug has been resolved in version 7. So my best advice is to skip version 6.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson