Skip to content

Instantly share code, notes, and snippets.

@Viiprogrammer
Last active February 12, 2023 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Viiprogrammer/c60c8d2c3a3c95c72b11c5ef0e232113 to your computer and use it in GitHub Desktop.
Save Viiprogrammer/c60c8d2c3a3c95c72b11c5ef0e232113 to your computer and use it in GitHub Desktop.
docusaurus-mermaid

I couldn't find any solution to use Mermaid without changing the theme to @docusaurus/theme-mermaid and trying to write a solution, and... it works great.

Create mermaid.js in /src/js/ and use it in MDX as below

(Don't forget remove .example extension from example.mdx.example)

import Mermaid from '@site/src/js/mermaid';
# Example graph
<Mermaid chart={`
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;
`}/>
import React, { useEffect, useRef, useState } from 'react'
import mermaid from 'mermaid'
import { useColorMode } from '@docusaurus/theme-common'
export default ({ chart }) => {
const ref = useRef(null)
const [id] = useState(
'mermaid-' + Math.random()
.toString(36)
.slice(4)
)
const { colorMode } = useColorMode()
useEffect(() => {
mermaid.mermaidAPI.initialize({
startOnLoad: true,
securityLevel: 'loose',
logLevel: 5
})
})
useEffect(() => {
if (ref.current && chart !== '') {
mermaid.mermaidAPI.render(
id, `%%{init: {'theme':'${colorMode === 'dark' ? 'dark' : 'neutral'}'}}%%` + chart,
result => {
ref.current.innerHTML = result
})
}
}, [chart, colorMode])
return <div key={id} ref={ref}/>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment