Mermaid MDX component

Mermaid is an awesome text based language for creating diagrams and charts. The component below wraps it so you use it from MDX.

$ npm i --save mermaid

Here's the React component we'll use. Mermaid.tsx:

import React, { useEffect } from "react";
import mermaid from "mermaid";
mermaid.initialize({
startOnLoad: true,
});
type MermaidProps = {
readonly chart: string;
};
const Mermaid = ({ chart }: MermaidProps): JSX.Element => {
useEffect(() => mermaid.contentLoaded(), []);
return <div className="mermaid">{chart}</div>;
};
export default Mermaid;

If you're using Next.js you'll need to use a dynamic import because of the way Mermaid loads its D3.js dependency.

import dynamic from "next/dynamic";
const Mermaid = dynamic(() => import("components/Mermaid"), {
ssr: false,
});

Then simply provide the component to your MDX renderer, for example, using Next MDX remote:

<MDXRemote {...content} components={[Mermaid]} />

Then use it in your MDX page

# Example markdown/MDX page with Mermaid
Here's my user journey:
<Mermaid chart={`
journey
title My working day
section Go to work
Make tea: 5: Me
Go upstairs: 3: Me
Do work: 1: Me, Cat
section Go home
Go downstairs: 5: Me
Sit down: 5: Me
`}/>

Here it is rendered: