Using mermaid in React

October 26th 2017

If you've not used mermaid before, it can save a significant amount of maintenance time in developing flowcharts, sequence, Gantt, or class diagrams.

It turns this:

graph TD;
A-->B;
A-->C;
B-->D;
C-->D;

into this:

A
B
C
D

To create a Mermaid React component add the package with yarn add mermaid and use the following:

1
import React, { Component } from 'react'
2
import PropTypes from 'prop-types'
3
import mermaid from 'mermaid'
4
5
class Mermaid extends Component {
6
constructor(props) {
7
super(props)
8
this.state = {
9
svg: null,
10
}
11
12
mermaid.mermaidAPI.initialize({
13
startOnLoad: false,
14
})
15
}
16
17
componentDidMount() {
18
mermaid.mermaidAPI.render(this.props.id, this.props.content, svg => {
19
this.setState({ svg })
20
})
21
}
22
23
render() {
24
if (!this.state.svg) {
25
return <div>Loading...</div>
26
}
27
28
return <div dangerouslySetInnerHTML={{ __html: this.state.svg }} />
29
}
30
}
31
32
Mermaid.propTypes = {
33
id: PropTypes.string.isRequired,
34
content: PropTypes.string.isRequired,
35
}
36
37
export default Mermaid

You can use the component like so:

1
const graph = `
2
graph TD;
3
A-->B;
4
A-->C;
5
B-->D;
6
C-->D;
7
`
8
9
<Mermaid id="graph1" content={graph} />

If you are having issues with rendering, you can set the mermaid logLevel in the mermaidAPI.initialize call to see additional output in the console:

1
mermaid.mermaidAPI.initialize({
2
startOnLoad: false,
3
+  logLevel: 1,
4
})