Importing Components into MDX Files

As we saw previously, we can import arbitrary React components into our Markdown documents, such as the Figure component we wrote earlier in this section:

---
title: Hello MDX!
date: 2021-04-19
---

import { Figure } from './components/figure';

# Hello MDX!

<ul>
  <li>Title: {props.pageContext.frontmatter.title}</li>
  <li>Date: {props.pageContext.frontmatter.date}</li>
</ul>

<Figure data="figure.svg" caption="An illustration of MDX in Markdown." />

Components used in MDX files can also be universally leveraged across a Gatsby site as shortcodes, thanks to the MDXProvider component. To make the Figure component available to all your MDX files, for instance, you could add the following inside your layout component:

// src/components/layout.js
import React from "react"
import { MDXProvider } from "@mdx-js/react"
import { Figure } from "./figure"

const shortcodes = { Figure }

export default function Layout({ children }) {
  return (
    <MDXProvider components={shortcodes}>{children}</MDXProvider>
  )
}

Any MDX components that are passed into MDXProvider as the components prop will be available to any MDX documents that are rendered by the provider. This means you no longer need to import the components manually within your MDX files:

---
title: Hello MDX!
date: 2021-04-19
---

# Hello MDX!

<ul>
  <li>Title: {props.pageContext.frontmatter.title}</li>
  <li>Date: {props.pageContext.frontmatter.date}</li>
</ul>

<Figure data="figure.svg" caption="An illustration of MDX in Markdown." />
NOTE

It’s also possible to use JavaScript exports directly within MDX files for other purposes, like exporting page metadata or defining a layout. For more information on these use cases, consult the Gatsby documentation’s section on using JavaScript exports in MDX. The documentation also contains information on lazy-loading components in MDX files for performance reasons.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *