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.
Install gatsby-plugin-mdx, the official plugin for using MDX with Gatsby. Also install
gatsby-plugin-feed-mdx for our RSS feeds. Finally, install
gatsby-plugin-mdx, along with the following changes:
For reference, here's the full configuration for
gatsby-plugin-feed-mdx. This will allow the RSS feed of the site to parse MDX.
Now, since we're no longer using
gatsby-plugin-feed, you can uninstall them.
allMdx in the
allMdx in the GraphQL query.
mdx in the
mdx in the GraphQL query.
Add an import statement for
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
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!