Skip to content

Instantly share code, notes, and snippets.

@yottahmd
Created August 19, 2021 01:43
Show Gist options
  • Save yottahmd/f20a53f08655918672bd4df4afaa0c4d to your computer and use it in GitHub Desktop.
Save yottahmd/f20a53f08655918672bd4df4afaa0c4d to your computer and use it in GitHub Desktop.
Wrapper component for mermaid.js to use in React+TS
import React, { useEffect, useRef, useState } from "react";
import mermaidAPI from "mermaid";
type Props = {
divId: string;
children: string;
};
export default function Mermaid({ children }: Props) {
const [html, setHtml] = useState<string>("");
const divRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!divRef.current) {
return;
}
try {
mermaidAPI.initialize({
securityLevel: "loose",
logLevel: 1,
startOnLoad: true,
flowchart: {
useMaxWidth: true,
htmlLabels: true,
},
});
mermaidAPI.render("mermaid", children, (svgCode, bindFunc) => {
setHtml(svgCode);
setTimeout(() => {
bindFunc(divRef.current!);
}, 500);
}, divRef.current);
} catch (error) {
console.error(error);
console.error(children);
}
}, [children, divRef]);
return (
<div
className="mermaid flex justify-center"
dangerouslySetInnerHTML={{ __html: html }}
ref={divRef}
>
</div>
);
}
@yottahmd
Copy link
Author

need to use setTimeout to bind click event with the svg after rendering.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment