0
0
AstroHow-ToBeginner ยท 3 min read

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/mdx or forgetting to add it to astro.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/mdx via npm.
  • Add mdx() to integrations in astro.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.