Zach Schnackel

MDX previews in Netlify CMS

MDX is an incredible toolkit that allows you to write JSX in your Markdown files; creating opportunities for more dynamic and interactive experiences in your content.

What's even better than the technology itself, is the ability it provides content-contributors to work alongside these advanced components within the articles they're crafting. When coupled with GUI interfaces like Netlify CMS, we're able to provide an abstraction-layer for whatever technology we're using.

Technology is only as good as the simplicity it introduces.

The problem

While Netlify CMS provides a wealth of features upfront that makes setup and creating collection-types easy, an assumption it doesn't make is within its preview-panel.

Netlify CMS: Before

This normally wouldn't be a huge deal. We're able to see the fields and parsed Markdown - albeit rough. But, as we look closer at the article, we can see some MDX components that either don't show anything at all or present a vastly different experience than what would be expected within the preview panel.

The solution

Luckily, Netlify CMS is pluggable, and allows us to hook into and generate our own previews per collection-type:

cms.js

In my case, I also wanted to wrap the iFrame that powers the preview and utilize Emotion, so a HOC was created to target and provide that scope:

withEmotion.js

Finally, we are ready to tackle the preview render:

MDXPreview.js

mdx-scoped-runtime comes to the rescue with the ability to parse MDX on-the-fly. We can then use this component alongside any other fields we want to display within our preview.

ArticlePreview.js
Netlify CMS: After

Gatsby tip

For scenarios where you may have components that use a bit more Gatsby magic than what mdx-scoped-runtime can provide; like graphql, you can override the default behavior to provide a fallback component as needed to avoid compilation errors:

MDXPreview.js
:: Published Jul 23, 2020 ::