Beyond basic MDX

MDX lets authors write Markdown while mixing in React components, which makes it a good fit for blogs, slide decks and component docs. The examples below assume GatsbyJS and React, but MDX can be written with other frameworks as well. This covers advanced extension points: layout defaults, element overrides, shortcodes and child manipulation.

Defining a default layout

MDX pages usually need to render inside a shared layout. With the gatsby-plugin-mdx plugin, a default Layout component can be set in config:

{
  resolve: `gatsby-plugin-mdx`,
  options: {
    defaultLayouts: {
      default: path.resolve('./src/templates/blog-post.js'),
    },
    // ...other options
  }
}

The referenced file, src/templates/blog-post.js, must contain a component that renders the children prop it receives:

import { MDXRenderer } from 'gatsby-plugin-mdx';


function BlogPost({ children }) {
  return (
    <div>{children}</div>
  );
}


export default BlogPost;

For pages created programmatically, the same result requires a component named MDXRenderer, as documented by Gatsby.

Replacing Markdown elements with custom components

By default, Markdown output maps to a known set of HTML elements:

NameHTML ElementMDX Syntax
Paragraph<p>
Heading 1<h1>#
Heading 2<h2>##
Heading 3<h3>###
Heading 4<h4>####
Heading 5<h5>#####
Heading 6<h6>######
Unordered List<ul>-
Ordered List<ol />1.
Image<img />![alt](https://image-url)
A complete list of components is available in the MDX Docs.

Rather than writing a remark plugin to change them, MDX ships an MDXProvider component. It uses the React Context API to inject custom components and merge them with MDX's defaults:

import React from 'react';
import { MDXProvider } from "@mdx-js/react";
import Image from './image-component';


function Layout({ children }) {
  return (
    <MDXProvider
      components={{
        h1: (props) => <h1 {...props} className="text-xl font-light" />
        img: Image,
      }} 
    >
      {children}
    </MDXProvider>
  );
}


export default Layout;

Here any H1 (#) in the MDX file uses the custom implementation passed as the provider's prop, while every other element falls back to the default. MDX merges the custom markup for one element into its defaults and applies it whenever the matching syntax appears.

Importing components versus shortcodes

A component can be imported into an MDX file like any other React component:

---
title: Importing Components
---
import Playground from './Playground';


Here is a look at the `Playground` component that I have been building:


<Playground />

That is fine for a one-off demo, but importing the same component into every post is tedious. MDX shortcodes solve this by exposing components to all documents in the app — the docs describe them as useful for common pieces like YouTube embeds or Twitter cards. Shortcodes are registered through MDXProvider too:

import React from 'react';
import { MDXProvider } from "@mdx-js/react";
import Playground from './playground-wrapper';


function Layout({ children }) {
  return (
    <MDXProvider
      components={{
        h1: (props) => <h1 {...props} className="text-xl font-light" />
        Playground,
      }} 
    >
      {children}
    </MDXProvider>
  );
}


export default Layout;

Once a component sits in the components object, it can be used in any MDX file without an import:

---
title: Demoing concepts
---


Here's the demo for the new concept:


<Playground />


> Look ma! No imports

Accessing children directly

React's React.Children APIs let you manipulate children — reorder them, pass new props, control visibility. MDX exposes the child components it passes in through a special wrapper component, added via MDXProvider as before:

import React from "react";
import { MDXProvider } from "@mdx-js/react";
const components = {
  wrapper: ({ children, ...props }) => {
    const reversedChildren = React.Children.toArray(children).reverse();
    return <>{reversedChildren}</>;
  },
};
export default (props) => (
  <MDXProvider components={components}>
    <main {...props} />
  </MDXProvider>
);

The example above reverses the children, so they render in the opposite order from how they were written. Animating every MDX child as it arrives is also possible:

import React from "react";
import { MDXProvider } from "@mdx-js/react";
import { useTrail, animated, config } from "react-spring";


const components = {
  wrapper: ({ children, ...props }) => {
    const childrenArray = React.Children.toArray(children);
    const trail = useTrail(childrenArray.length, {
      xy: [0, 0],
      opacity: 1,
      from: { xy: [30, 50], opacity: 0 },
      config: config.gentle,
      delay: 200,
    });
    return (
      <section>
        {trail.map(({ y, opacity }, index) => (
          <animated.div
            key={index}
            style={{
              opacity,
              transform: xy.interpolate((x, y) => `translate3d(${x}px,${y}px,0)`),
            }}
          >
            {childrenArray[index]}
          </animated.div>
        ))}
      </section>
    );
  },
};


export default (props) => (
  <MDXProvider components={components}>
    <main {...props} />
  </MDXProvider>
);

What this enables

With gatsby-plugin-mdx, the techniques above cover four tasks:

  1. Defining default Layout components to format MDX output.
  2. Swapping the default HTML elements generated from Markdown for custom components.
  3. Using shortcodes so components need not be imported in every file.
  4. Manipulating children directly to alter the MDX output.

These are only a subset of what MDX offers for making content authoring on static sites easier.