How to Use MDX with Astro: Simple Guide for Beginners
To use
MDX with Astro, install the @astrojs/mdx integration and add it to your astro.config.mjs. Then import .mdx files as components in your Astro pages to render Markdown with embedded JSX.Syntax
First, install the MDX integration package. Then, add it to your Astro config file. Import MDX files like components and use them in your Astro pages.
- Installation: Adds MDX support.
- astro.config.mjs: Registers MDX integration.
- Import: Use
import Content from './file.mdx'. - Usage: Render with
<Content />.
bash and javascript
npm install @astrojs/mdx // astro.config.mjs import { defineConfig } from 'astro/config'; import mdx from '@astrojs/mdx'; export default defineConfig({ integrations: [mdx()], }); // In your Astro page --- import Content from '../content/example.mdx'; --- <Content />
Example
This example shows how to create an MDX file with Markdown and JSX, then import and render it in an Astro page.
mdx and astro
--- export const frontmatter = { title: 'Hello MDX in Astro', }; --- # Welcome to MDX This is Markdown content with <strong>JSX</strong> support. <button onClick={() => alert('Clicked!')}>Click me</button> // src/pages/index.astro --- import Content from '../content/example.mdx'; --- <html lang="en"> <head> <title>MDX with Astro</title> </head> <body> <Content /> </body> </html>
Output
<h1>Welcome to MDX</h1>
<p>This is Markdown content with <strong>JSX</strong> support.</p>
<button>Click me</button>
Common Pitfalls
- Not installing
@astrojs/mdxor forgetting to add it toastro.config.mjs. - Importing MDX files without the correct relative path.
- Using JSX inside MDX without wrapping event handlers in functions.
- Forgetting to restart the Astro dev server after adding the integration.
javascript
// Wrong: Missing integration in astro.config.mjs // astro.config.mjs export default { // no mdx integration }; // Right: Add MDX integration import mdx from '@astrojs/mdx'; export default { integrations: [mdx()], };
Quick Reference
Summary tips for using MDX with Astro:
- Install
@astrojs/mdxvia npm. - Add
mdx()tointegrationsinastro.config.mjs. - Import MDX files as components in Astro pages.
- Use JSX inside MDX for interactive UI.
- Restart dev server after setup changes.
Key Takeaways
Install and add @astrojs/mdx integration in astro.config.mjs to enable MDX support.
Import .mdx files as components and render them in Astro pages with syntax.
Use JSX inside MDX for interactive elements like buttons and event handlers.
Always restart the Astro dev server after adding or changing integrations.
Check file paths carefully when importing MDX files to avoid errors.