Using MDX

What Is MDX?

MDX to markdown is the same as JSX to JS. To quote the original site,

MDX is an authorable format that lets you seamlessly write JSX in your Markdown documents. You can import components, such as interactive charts or alerts, and embed them within your content. This makes writing long-form content with components a blast 🚀.

... and this one:

Writing is fun again when you combine components, that can even be dynamic or load data, with the simplicity of Markdown for long-form content.

Basically, renaming your .md file to .mdx gives you ability to import and use React components as if it was a normal React or Next.js app.

Here is a small demo video for curious:

Using Custom Components

Say we have a basic React counter component like this:

components/example-counter.jsx
1import React, { useState } from 'react'
2export default function Counter() {
3  const [count, setCount] = useState(0)
4
5  return (
6    <div className='border border-gray-500 p-2 m-10 rounded-md bg-gray-700 text-gray-100'>
7      <p>You clicked {count} times!</p>
8      <button
9        onClick={() => setCount(count + 1)}
10        className='rounded border border-gray-500 bg-gray-900 p-1 mt-2'
11      >
12        Click me
13      </button>
14    </div>
15  )
16}

If you need to use components in your markdown content files, use .mdx extension, and provide any custom components through the components/component-mapper.jsx file. Then include it in your .mdx file and display it just like in React application:

1### Example Counter Component
2<Counter />

becomes:

Example Counter Component

You clicked 0 times!

Voila! This way you can create dynamic components for your documentation like never before. Live code editors, quizes, exams, cheatsheets, comments, you name it. Possibilities are endless. Notice that you can use tailwindcss classnames in components for styling.

More MDX Wizardry

For more information what can be achieved with MDX, see the official site.