What is MDX?
MDX is a file format that lets you add JSX to Markdown files via a .mdx
file! It was started by and is maintained by Gatsby’s John Otander and the open source community on GitHub.
With MDX, you can import React components and declare them alongside regular markdown syntax with JSX. This is useful to display specific component examples alongside the actual code, complex interactive components like charts, reusable components across multiple pages like sign-up forms, and more!
Adding MDX to Gatsby Starter Blog
It can be a big tricky to add MDX to an existing blog. The following 5 steps will cover how to install and configure MDX to work with Gatsby’s blog starter, which as of today’s version, does not have MDX pre-installed.
You can also see the full changes in PR #19580 for an overview of the changes you have to make to get MDX working. As stated above, this introduces changes to Gatsby’s blog starter, which you can install with Gatsby CLI.
Step 1
Install gatsby-plugin-mdx, the official plugin for using MDX with Gatsby. Also install gatsby-plugin-feed-mdx
for our RSS feeds. Finally, install @mdx-js/mdx
and @mdx-js/react
.
Step 2
In gatsby-config.js
, replace gatsby-transformer-remark
with gatsby-plugin-mdx
, along with the following changes:
For reference, here’s the full configuration for gatsby-plugin-mdx
.
Then, replace gatsby-plugin-feed
with gatsby-plugin-feed-mdx
. This will allow the the RSS feed of the site to parse MDX.
Now, since we’re no longer using gatsby-transformer-remark
and gatsby-plugin-feed
, you can uninstall them.
Step 3
In gatsby-node.js
, replace allMarkdownRemark
with allMdx
.
Next, replace MarkdownRemark
with Mdx
.
Step 4
In src/pages/index.js
, replace allMarkdownRemark
with allMdx
in the render()
method.
Also replace allMarkdownRemark
with allMdx
in the GraphQL query.
Step 5
In src/templates/blog-post.js
, replace markdownRemark
with mdx
in the render()
method.
Also replace markdownRemark
with mdx
in the GraphQL query.
Add an import statement for MDXRenderer
from gatsby-plugin-mdx
.
We’ll be using body
instead of html
in our GraphQL query.
Now we can replace the <section>
element with the dangerouslySetInnerHTML
attribute and instead use <MDXRenderer>
with post.body
.
And… that’s it! After these changes, a Gatsby blog should be able to use MDX files to render JSX alongside markdown. To test that everything works, add a .mdx
file to [your-blog]/content/blog/
and write some JSX. Then, run gatsby develop
and check http://localhost:8000/blog/
for your new post. The JSX should rendered as an element on the new post page.
For example, the following code should render a test button. Navigate to http://localhost:8000/blog/example/
and you should see a clickable button in your blog post!
If you’re interested in spinning up a new personal blog with MDX, I’ve prepared Gatsby personal blog starter for your usage!