Chuyển đến nội dung

Bài 24 · Markdown and MDX Sites

MDX in Gatsby: Components Inside Markdown

Set up gatsby-plugin-mdx, write MDX with React components and imports, map HTML elements to your own components, and render MDX pages with a template.

Plain Markdown is great until you need something interactive: a live chart, a call-out box, a tabbed code sample. MDX is Markdown that also understands JSX. You can import a React component and use it between paragraphs, or export values from the file. Gatsby supports MDX through gatsby-plugin-mdx.

This lesson targets gatsby-plugin-mdx version 5 (with Gatsby 5). Earlier versions used a different approach (body and MDXRenderer), so check your version before copying old tutorials.

Install and configure

JavaScript
// gatsby-config.js (real Gatsby, read-only)
module.exports = {
  plugins: [
    { resolve: "gatsby-source-filesystem", options: { name: "posts", path: `${__dirname}/content/posts` } },
    {
      resolve: "gatsby-plugin-mdx",
      options: {
        extensions: [".mdx", ".md"],
        mdxOptions: {
          remarkPlugins: [require("remark-gfm")],
          rehypePlugins: [],
        },
      },
    },
  ],
}

gatsby-plugin-mdx needs gatsby-source-filesystem for the files and @mdx-js/react for the provider. The mdxOptions object is passed to the MDX compiler, so any remark or rehype plugin works there (GitHub tables need remark-gfm).

Writing MDX

MDX
---
title: "Charts in posts"
slug: charts-in-posts
date: 2025-04-01
---

import { Callout } from "../../src/components/callout"

# Charts in posts

Regular Markdown works: **bold**, lists and `code`.

<Callout type="tip">
  This is a React component inside a Markdown file.
</Callout>

export const stats = { readers: 1200 }

We have {stats.readers} readers.

Imports and exports go at the top level, JSX is allowed in blocks, and curly braces evaluate JavaScript expressions. Leave a blank line between JSX and Markdown text, otherwise the Markdown inside the component is not parsed.

Rendering MDX with a template

Version 5 compiles each file into a React component. A page template receives it as children. You must tell Gatsby which MDX file to compile by appending ?__contentFilePath= to the template path:

JavaScript
// gatsby-node.js (real Gatsby, read-only)
const path = require("path")
const template = path.resolve("src/templates/post.js")

exports.createPages = async ({ graphql, actions }) => {
  const result = await graphql(`
    { allMdx { nodes { id frontmatter { slug } internal { contentFilePath } } } }
  `)
  result.data.allMdx.nodes.forEach((node) => {
    actions.createPage({
      path: `/blog/${node.frontmatter.slug}/`,
      component: `${template}?__contentFilePath=${node.internal.contentFilePath}`,
      context: { id: node.id },
    })
  })
}
JSX
// src/templates/post.js (real Gatsby, read-only)
import * as React from "react"
import { graphql } from "gatsby"

export default function Post({ data, children }) {
  return (
    <article>
      <h1>{data.mdx.frontmatter.title}</h1>
      {children}
    </article>
  )
}

export const query = graphql`
  query ($id: String!) {
    mdx(id: { eq: $id }) { frontmatter { title } }
  }
`

There is also the file system route API: a file named src/pages/blog/{mdx.frontmatter__slug}.js creates one page per MDX node automatically, with no createPages code. It still receives children.

Mapping elements to your components

Wrap pages with MDXProvider and pass a components map. Any HTML element Markdown produces (h2, a, pre, table) can be replaced, and extra names can be provided so authors do not need to import them.

JSX
// real Gatsby, read-only: wrapPageElement in gatsby-browser.js and gatsby-ssr.js
import { MDXProvider } from "@mdx-js/react"
import { Callout } from "./src/components/callout"
import { StyledLink } from "./src/components/link"

const components = { a: StyledLink, Callout }

export const wrapPageElement = ({ element }) => (
  <MDXProvider components={components}>{element}</MDXProvider>
)

Put the same code in both gatsby-browser.js and gatsby-ssr.js, so server HTML and client agree. After this, writing <Callout> in any MDX file works without an import.

How MDX works (stand-in)

MDX compiles each file to a function that returns React elements, replacing tag names with entries from components. The stand-in below shows that lookup with plain strings.

JS Stand-in: swapping tags for components

Press Run (or Ctrl + Enter) to see the console output here.

No output.

And a tiny parser for the "JSX in Markdown" idea: finding <Name attr="x">...</Name> blocks and handing them to a component.

JS Stand-in: expand custom tags in text

Press Run (or Ctrl + Enter) to see the console output here.

No output.

MDX or Markdown?

Use plain Markdown (remark) when posts are simple and authors are not developers: it is faster to build and safer. Choose MDX when posts need interactive demos or reusable layout pieces. A common mix is Markdown for most content and MDX for a few rich articles.

Common mistakes

  • Missing ?__contentFilePath= on the template path: the page renders without content.
  • Using curly braces for literal text, such as {like this}; escape with a backslash or use inline code.
  • Forgetting a blank line after an opening JSX tag.
  • Providing components only in the browser file and not in gatsby-ssr.js, which causes hydration mismatches.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. How does a Gatsby 5 page template receive the compiled MDX content?

    In gatsby-plugin-mdx v5 the compiled MDX is passed to the template as children.
  2. 2. What does the __contentFilePath query string tell Gatsby?

    It is appended to the template path so the plugin knows which file to render.
  3. 3. What is MDXProvider used for?

    MDXProvider supplies a components map used when rendering MDX.

Summary

  • MDX lets Markdown use imports, exports, JSX and expressions.
  • gatsby-plugin-mdx v5 renders each file as children of a template; use ?__contentFilePath= in createPages, or the file system route API.
  • MDXProvider with wrapPageElement (browser and SSR) maps elements to components.
  • Prefer plain Markdown for simple posts.

Next: Front matter, tags and pagination

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.