Skip to main content

Importing and Using Components in MDX

You can import your components from other third party libraries, like theme-ui. Use cases for external libraries could be charting libraries for adding rich data visualizations, form components for adding email signups, styled portions of content like pullquotes, or call to action buttons throughout your pages. You can also import and reuse your own React components and MDX documents.

Import components for use from another library

Components imported from other libraries can be rendered inline with your markdown content, allowing you to include rich media like charts, interactive buttons, or styled messages. Components are imported at the top of your MDX documents—in the same syntax they are imported in JavaScript files—and then added using opening and closing brackets like normal JSX elements.

To include a component from another library (this example uses the message component from theme-ui), you need to import it at the top of your MDX file:

Note: steps for importing custom components or MDX documents from a relative location in your project are also covered in the Writing Pages in MDX guide.

Make components available globally as shortcodes

To avoid having to import the same component inside of every MDX document you author, you can add components to an MDXProvider to make them globally available in MDX pages. This pattern is sometimes referred to as shortcodes.

All MDX components passed into the components prop of the MDXProvider will be made available to MDX documents that are nested under the provider. The MDXProvider in this example is in a layout component that wraps all MDX pages, you can read about this pattern in the layout section of the gatsby-plugin-mdx README.

Now, you can include components in your MDX without importing them:

Because the <Message /> and <Chart /> components were passed into the provider, they are available for use in all MDX documents.

Edit this page on GitHub