Astro MDX components can replace the HTML that Markdown produces. Pass an object to the components prop of <Content />, such as components={{ h2: Heading, a: Link, img: Figure }}, and every ## heading, link and image in your MDX files renders through your component instead of a plain tag. You can also make components like Callout available in every post without an import line.
This guide shows how the mapping works, what props each component receives, and patterns for headings, links, images, code blocks and tables.
Key Takeaways
- Element mapping works in
.mdxfiles only. Plain.mdfiles ignore thecomponentsprop.- Map elements where you render content:
<Content components={{ h2: H2 }} />.- Your component receives the element’s attributes as props (
href,id,src,alt) and its content as the default slot.- Non-HTML names in the object, like
Callout, become globally available tags in every MDX file rendered that way.- An MDX file can also
export const components = { ... }to set mappings for itself.
How MDX element mapping works
When MDX compiles a file, every Markdown construct becomes a JSX element: ## Setup becomes <h2>, [docs](/docs/) becomes <a>, and so on. Before rendering, MDX looks each tag name up in a components object. If it finds an entry, it renders that component instead of the plain HTML tag.
In Astro, you supply that object when rendering:
---
// src/pages/blog/[id].astro
import { getCollection, render } from 'astro:content';
import H2 from '../../components/mdx/H2.astro';
import H3 from '../../components/mdx/H3.astro';
import Link from '../../components/mdx/Link.astro';
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((post) => ({ params: { id: post.id }, props: { post } }));
}
const { post } = Astro.props;
const { Content } = await render(post);
---
<article class="prose">
<Content components={{ h2: H2, h3: H3, a: Link }} />
</article>
This requires the MDX integration (npx astro add mdx). If you’re new to MDX itself, start with the Astro MDX guide.
Mappable elements
| Markdown | Element key | Props your component gets |
|---|---|---|
# Title to ###### Title |
h1 to h6 |
id (generated slug) |
[text](url) |
a |
href, title |
 |
img |
src, alt, title |
> quote |
blockquote |
none |
- item / 1. item |
ul, ol, li |
none |
| fenced code | pre, code |
Shiki attributes on pre |
`code` |
code |
none |
| tables | table, thead, tbody, tr, th, td |
alignment |
--- |
hr |
none |
| paragraphs | p |
none |
Each component receives the element’s text and children through <slot />. Destructure the attributes you need from Astro.props and spread the rest so nothing is lost.
Headings with anchor links
Astro adds an id to every heading so table-of-contents links work. A custom heading can turn that into a visible anchor. A component mapped to several heading levels can’t tell which tag it replaced, so the simplest approach is one tiny component per level:
---
// src/components/mdx/H2.astro
import type { HTMLAttributes } from 'astro/types';
type Props = HTMLAttributes<'h2'>;
const { id, ...rest } = Astro.props;
---
<h2 id={id} class="heading" {...rest}>
<a href={`#${id}`} class="heading__anchor" aria-hidden="true" tabindex="-1">#</a>
<slot />
</h2>
Create H3.astro the same way and map { h2: H2, h3: H3 }. Because the id is unchanged, render()’s headings array still matches, so a generated table of contents keeps working. The heading anchor links tip shows a version with a copy-link button.
Links that handle external URLs
A link component can add rel and a visual marker to external links while leaving internal ones alone:
---
// src/components/mdx/Link.astro
import type { HTMLAttributes } from 'astro/types';
type Props = HTMLAttributes<'a'>;
const { href = '', ...rest } = Astro.props;
const url = String(href);
const isExternal = /^https?:\/\//.test(url) && !url.startsWith(Astro.site?.origin ?? '__none__');
---
<a
href={url}
{...rest}
{...(isExternal ? { rel: 'noopener noreferrer', target: '_blank' } : {})}
>
<slot />
{isExternal && <span class="sr-only"> (opens in a new tab)</span>}
</a>
The screen-reader text keeps the new-tab behavior accessible. Whether external links should open in new tabs at all is a judgment call; the external links tip weighs both sides.
Images as figures with captions
Markdown has no caption syntax, but the image title makes a good one: .
---
// src/components/mdx/Figure.astro
import { Image } from 'astro:assets';
import type { ImageMetadata } from 'astro';
interface Props {
src: ImageMetadata | string;
alt: string;
title?: string;
}
const { src, alt, title } = Astro.props;
---
<figure>
{typeof src === 'string'
? <img src={src} alt={alt} loading="lazy" decoding="async" />
: <Image src={src} alt={alt} widths={[480, 800, 1200]} sizes="(min-width: 800px) 800px, 100vw" />}
{title && <figcaption>{title}</figcaption>}
</figure>
Map it with img: Figure. For local images, Astro’s MDX integration has already resolved the file, so src arrives as image metadata you can hand to <Image /> for optimization. Remote URLs arrive as strings. The image captions tip covers the plain Markdown equivalent.
Code blocks with a copy button
Shiki renders fenced code to a <pre> with styling attributes. Wrap it rather than replacing its contents:
---
// src/components/mdx/Pre.astro
const props = Astro.props;
---
<div class="code-block">
<pre {...props}><slot /></pre>
<button type="button" class="code-block__copy" aria-label="Copy code">Copy</button>
</div>
<script>
document.querySelectorAll<HTMLButtonElement>('.code-block__copy').forEach((button) => {
button.addEventListener('click', async () => {
const code = button.previousElementSibling?.textContent ?? '';
await navigator.clipboard.writeText(code);
button.textContent = 'Copied';
setTimeout(() => (button.textContent = 'Copy'), 1500);
});
});
</script>
Spreading props onto the inner <pre> keeps Shiki’s classes and inline styles, so highlighting is unaffected. Map it with pre: Pre. The copy code button walkthrough builds a fuller version.
Responsive tables
Wide tables overflow on phones. Wrapping them in a scroll container fixes it everywhere at once:
---
// src/components/mdx/Table.astro
---
<div class="table-wrap" role="region" aria-label="Scrollable table" tabindex="0">
<table {...Astro.props}><slot /></table>
</div>
<style>
.table-wrap { overflow-x: auto; }
</style>
tabindex="0" lets keyboard users scroll the region.
Global components without imports
Any key that isn’t an HTML element name becomes a component authors can use directly in MDX:
---
// src/layouts/PostLayout.astro (frontmatter excerpt)
import { render, type CollectionEntry } from 'astro:content';
import Callout from '../../components/Callout.astro';
import YouTube from '../../components/YouTube.astro';
import H2 from '../../components/mdx/H2.astro';
import Figure from '../../components/mdx/Figure.astro';
const { post } = Astro.props as { post: CollectionEntry<'blog'> };
const mdxComponents = { h2: H2, img: Figure, Callout, YouTube };
const { Content } = await render(post);
---
<Content components={mdxComponents} />
Now any post can write <Callout type="tip">...</Callout> with no import. That’s convenient for authors, but it hides where components come from, so keep the list short and documented.
Keep the mapping object in one module and import it into every layout that renders MDX, so blog posts, docs pages and tips all behave the same way.
Per-file mappings with export
A single MDX file can set its own mappings by exporting components:
---
title: Changelog
---
import Release from '../../components/Release.astro';
export const components = { h2: Release };
## 7.4.0
Build timings and parallel prerendering.
Every ## in that file renders as a Release component. Keep per-file and <Content /> mappings for different elements, so it’s always clear which one applies.
Gotchas
A few things catch people out:
.mdfiles ignore mappings. Rename to.mdx, or use a rehype plugin for Markdown files.- The
optimizeoption. Withmdx({ optimize: true }), static parts of MDX become plain HTML strings and skip mapped components. List the elements you map inoptimize: { ignoreElementNames: ['h2', 'img'] }. - Forgetting
<slot />. Without it, the element’s text disappears. - Dropping attributes. Always spread remaining props, or you’ll lose ids, classes and Shiki styles.
The official MDX integration docs describe the components prop. Several Astro blog themes already map headings, images and code blocks this way, and the content docs explain how collections are rendered in a theme.
FAQ
How do I use custom components for Markdown elements in Astro?
Use MDX, then pass a components object to the rendered content: <Content components={{ h2: MyHeading, a: MyLink }} />. Each key is an HTML element name produced by Markdown, and each value is the component that should render it.
Can I map components in plain Markdown files in Astro?
No. The components prop only affects .mdx files. For .md files, change the output with a rehype plugin instead, or rename the files to .mdx and install @astrojs/mdx.
How do I use a component in MDX without importing it?
Add it to the components object you pass to <Content />, using its component name as the key, for example { Callout }. Every MDX file rendered through that layout can then use <Callout> without an import line.
What props does a custom MDX heading component receive?
It receives the heading’s id, which Astro generates from the heading text, plus any other attributes, with the heading text available through <slot />. Keep the id on the rendered element so table-of-contents links still work.
Why are my custom MDX components not rendering?
Check that the file is .mdx, that you passed the object to <Content components={...} />, and that the component renders <slot />. If optimize is enabled in the MDX integration, add the mapped element names to ignoreElementNames.