Convert an existing Gatsby Markdown blog to use MDX
Updated: August 4, 2020I've recently released a new version of my personal website and I decided to convert my posts from an existing Gatsby Markdown format to MDX.
MDX is usually called the markdown for the component era and it's a great way to write a document using JSX in Markdown. Additionally, if you work on a React project, you can even import existing components inside your MDX files.
Let's get started!
Step 1
In order to use MDX with Gatsby, you need to install @mdx-js/mdx
, @mdx-js/react
and the official Gatsby plugin gatsby-plugin-mdx
:
Step 2
Inside your gatsby-config.js
file, replace gatsby-transformer-remark
with gatsby-plugin-mdx
:
and plugins
with gatsbyRemarkPlugins
:
My configured gatsby-plugin-mdx
looks like this:
Step 3
Once we've refactored the gatsby-config.js
file, it's time to work with gatsby-node.js
.
Here, we need to replace allMarkdownRemark
with allMdx
:
Step 4
The final step consists in refactoring the template file that is used to generate the blog posts.
Head over to the template, in my case src/templates/postTemplate.js
, and import MDXRenderer
from the gatsby-plugin-mdx
plugin that we installed earlier:
Then, replace markdownRemark
with mdx
in the render()
method:
Finally, refactor the GraphQL query by using mdx
instead of markdownRemark
and body
instead of html
:
The refactored post query will look like this:
and the template component:
This is it! From now on, anytime you want to create a blog post, remember to use the .mdx
extension.