By Paul Scanlon


Let’s back track for just a second… What is MDX?

To quote the creators;

MDX is an authorable format that lets you seamlessly use JSX in your markdown documents. You can import components, like interactive charts or notifications, and export metadata. This makes writing long-form content with components a blast.

To put that into context you can import and use a React component in this post like this 👇

import { WordCountChart } from '../../../components/word-count-chart';

<WordCountChart title='Average word count' dimension='words' config={{ year: 0, color: 'primary' }} />;

The one snag, and it’s a tiny drawback is that to use React components in MDX you have to import them. This is fine for one off components but for common components adding an import to every post is a hassle. Fortunately using the MDXProvider you can provide your blog with a kind of “global” way to handle components without needing to import them every time you want to use them… which is very handy indeed. 😊

Setting up a “global” method is fine if you’re adding your own components but it’s a lot more work to do this if you want to “embed” media content from providers like Twitter, YouTube and Instagram

Gatsby MDX Embed

Luckily for you i’ve created gatsby-mdx-embed

gatsby-mdx-embed works by wrapping the root element of your site or blog with a custom MdxProvider which makes it possible for embed codes like this 👇

<Tweet tweetId='PaulieScanlon/status/1232993668690259968' />

To be automatically rendered. Like this 👇

A lof of media providers e.g YouTube make embed-able iframe embed codes which i’ve turned in to custom components specifically designed to work with Gatsby and MDX.

These media provider embed codes usually require you to add some kind of JavaScript to your page which can be really tricky to set up, but with this plugin all you need to do is install it…

npm install @pauliescanlon/gatsby-mdx-embed --save

… and then add it to gatsby-config.js and you’re good to go.

// gatsby.config.js

module.exports = {
  plugins: [`@pauliescanlon/gatsby-mdx-embed`]

There’s more

An extra trick i’ve used is to search the DOM for short codes that will require the provider scripts and if they aren’t found the provider scripts aren’t injected.

So if you’re not using embedded Tweets the Twitter provider script won’t be injected… keeping your site blazing fast ⚡

There’s currently 22 components to choose from and more are on the way so head on over to gatsby-mdx-embed and if you can please do give it a star ⭐ on GitHub

Screenshot of MDX Embed

This plugin was inspired by gatsby-remark-oembed which similarly provides an easy way to embed media from providers like YouTube, Twitter, etc into your blog without import. However this plugin only works with markdown.


Leave a reaction and let me know how I'm doing.

  • 0
  • 0
  • 0
  • 0
  • 0
Powered byNeon