Introduction
Mermaid is quite useful, no doubt about that. It might also be useful to display diagrams in a SharePoint Online site. So, why not displaying a mermaid diagram in an SPFx web part?
If you don’t know Mermaid you can have a look here.
Visual appearance
Let’s start having a look at a sample solution I’ve prepared. The solution is composed of a web part that allows, through the property pane, to configure the diagram to be shown.
You can find the code here.
First of all, in the following screenshot, you can see how the web part displays:
This web part, as said, is configured through the property pane:
The property pane allows to configure different properties divided in two different sections:
-
Configuration-
Title: the title to be displayed for the web part. -
MermaidDiagram: the actual Mermaid diagram to be displayed.
-
-
Styling-
Show Title: allow to hide or display the title of the web part. -
Show Border: allow to hide or show the border of the web part.
-
To have a better user experience, I’ve used the
PropertyFieldCodeEditor(more here) from the PnP reusable property pane controls (more here) in order to allow code editing inside the property pane.
For example, it’s possible to specify a Mermaid code in the property pane with a very nice code editor:
Once set the Mermaid diagram, you can have it displayed directly in the web part:
If you want some more idea of the capabilities, have a look at the readme file of the project here.
Show me the code
Now that you have a clear understanding of the appearance of the web part, let’s cover how to implement it.
To render a Mermaid diagram, first you need to install the mermaid package:
npm i mermaid
I won’t cover all the code here, if you’re interested in having a look at the whole project you can find it here.
After installing the package, you need to import it into your component:
import mermaid from 'mermaid';
After importing the package, you will need to initialize Mermaid:
mermaid.initialize({
startOnLoad: false,
theme: 'default',
securityLevel: 'strict',
htmlLabels: false
});
After initialization, you can use the package to render the actual SVG and insert it into the target HTML element:
const { svg } = await mermaid.render(
diagramId,
this.props.mermaidDiagram
);
The arguments for the Mermaid render method are:
-
diagramId: which is simply a unique ID for the diagram. -
this.props.mermaidDiagram: is the actual text of the Mermaid diagram to be rendered.
After the generation of the Mermaid diagram it’s a simple matter of showing it in the web part:
this.diagramRef.current.innerHTML = svg;
Conclusions
I think that Mermaid is pretty useful and powerful, particularly when it comes to visualizing complex data and workflows. It can be a very interesting addition to your SharePoint Online site, as it allows users to create diagrams and flowcharts with ease, enhancing the overall user experience.
Hope this helps!




Top comments (0)