Open m-s-abeer opened 11 months ago
import React, { useState, useRef, useEffect, Fragment, useCallback } from "react";
import MarkdownPreview from '@uiw/react-markdown-preview';
import { getCodeString } from 'rehype-rewrite';
import mermaid from "mermaid";
const randomid = () => parseInt(String(Math.random() * 1e15), 10).toString(36);
const Code = ({ inline, children = [], className, ...props }) => {
const demoid = useRef(`dome${randomid()}`);
const [container, setContainer] = useState(null);
const isMermaid = className && /^language-mermaid/.test(className.toLocaleLowerCase());
const code = props.node && props.node.children ? getCodeString(props.node.children) : children[0] || '';
const reRender = async () => {
if (container && isMermaid) {
try {
const str = await mermaid.render(demoid.current, code);
container.innerHTML = str.svg;
} catch (error) {
container.innerHTML = error;
}
}
}
useEffect(() => {
reRender()
}, [container, isMermaid, code, demoid]);
const refElement = useCallback((node) => {
if (node !== null) {
setContainer(node);
}
}, []);
if (isMermaid) {
return (
<Fragment>
<code id={demoid.current} style={{ display: "none" }} />
<code ref={refElement} data-name="mermaid" />
</Fragment>
);
}
return <code>{children}</code>;
};
const source = `
\`\`\`mermaid
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;
\`\`\`
`;
export default function Demo() {
return (
<MarkdownPreview
source={source}
components={{
code: Code
}}
/>
);
}
This is the code I'm rendering with:-
The md text I'm rendering with:-
It just renders it like this:-![image](https://github.com/uiwjs/react-markdown-preview/assets/35918365/f5174766-e7b8-463d-9972-5d03df3bf538)