Astro Custom Component in MDX

Introduction

Using MDX in Astro gives me a lot of flexibility, but for most posts I still want to write with standard Markdown syntax — images, code blocks, lists, etc. Is there a way to map custom components to Markdown syntax so I don’t have to import components in every MDX file and can just write pure Markdown? Actually, the Astro docs🔗 mention this.

Replacing MDX Elements with Custom Components

The Astro docs🔗 mention that you can output the Markdown you want to replace🔗 as specific components, but doing so requires importing and using the components in each MDX file, which isn’t very useful.

import Blockquote from '../components/Blockquote.astro';
export const components = {
blockquote: Blockquote,
};

Replacing All MDX with Custom Components

If your posts use Content Collections🔗, you can pass custom components when rendering the page content.

---
const { Content } = await post.render();
---
<Content components={{ Info, Video, img: PostImage, blockquote: PostBlockquote }} />

Utlizing this approach, I replaced all images on this blog with a custom image component🔗 to consistently handle size, compression, and styling, and plain Markdown syntax becomes more broadly usable.

Further Reading

Astro MDX Components🔗 - kizu.dev