Created
          August 19, 2021 01:43 
        
      - 
      
 - 
        
Save yottahmd/f20a53f08655918672bd4df4afaa0c4d to your computer and use it in GitHub Desktop.  
    Wrapper component for mermaid.js to use in React+TS
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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> | |
| ); | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
need to use setTimeout to bind click event with the svg after rendering.