Developments in Digital
Developments in Digital

Using mermaid in React

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:

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

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

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import mermaid from 'mermaid'

class Mermaid extends Component {
  constructor(props) {
    super(props)
    this.state = {
      svg: null,
    }

    mermaid.mermaidAPI.initialize({
      startOnLoad: false,
    })
  }

  componentDidMount() {
    mermaid.mermaidAPI.render(this.props.id, this.props.content, svg => {
      this.setState({ svg })
    })
  }

  render() {
    if (!this.state.svg) {
      return <div>Loading...</div>
    }

    return <div dangerouslySetInnerHTML={{ __html: this.state.svg }} />
  }
}

Mermaid.propTypes = {
  id: PropTypes.string.isRequired,
  content: PropTypes.string.isRequired,
}

export default Mermaid

You can use the component like so:

const graph = `
graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
`

<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:

mermaid.mermaidAPI.initialize({
  startOnLoad: false,
  logLevel: 1,
})