Published on

How to add Mermaid support to MDX in Tailwind NextJS Starter Blog


To write my blog I'm using Tailwind NextJS Starter Blog. It's pretty easy, basically you write in markdown or in mdx and everything just works.

Althought Tailwind NextJS Starter Blog is really AWESOME, does not cover everything that is in my mind nor my whims. And one of my whims is to use Mermaid.js to make diagrams. I use it every day, it's perfect to document processes, and as is text, can be versioned in Git, so fits perfectly for me.

These are the steps I did to add support for Mermaid.js in Tailwind NextJS Starter Blog

Install Mermaid

That's the easiest part, just run:

npm install --save mermaid

Create a component to render Mermaid

This is the complex part. Just create a new file /components/Mermaid.js and paste the following code

import React from 'react'
import mermaid from 'mermaid'

  startOnLoad: true,
  theme: 'default',

export default class Mermaid extends React.Component {
  componentDidMount() {
  render() {
    return <div className="mermaid">{this.props.chart}</div>

Mermaid process everything that it's under a CSS class mermaid, so basically this component just initialize mermaid and creates a div with a CSS class mermaid, in which the mermaid syntax will be finally placed.

Allow MDX to use the new Mermaid component

Before using the component directly, we must configure the MDX Component to allow it. That's pretty simple too, just open components/MDXComponents.js and add the new Mermaid component to the MDXComponents array:

import Mermaid from './Mermaid'

export const MDXComponents = {
  a: CustomLink,

How to use it

Now you should be able to render Mermaid charts in your MDX! It's as easy as this:

    flowchart LR
      UserService --> |depends on|OrganizationService
      OrganizationService --> |depends on|UserService

That code will render this

You can create really complex charts with Mermaid, like this:

Which corresponds to the following code:

  class GeoPointType {
  class GeoPoint {
    -UUID id
    +GeoPointType type
    +GeographyPoint location
    -UUID metadata references metadata(id)
    +Datetime createdAt
  class GeographyPoint {
    +GeoJSON geojson
    +Int srid
    +Float longitude
    +Float latitude
  class NearbyPoint {
    -UUID id references GeoPoint(id)
    +GeoPointType GeoPoint::type
    +GeographyPoint GeoPoint::location
    +UUID GeoPoint::metadata
    +Float distance
  class NearbyPoints {
    +GeoJSON origin
    +Float radiusMi
    +Int first
    +Int last
    +Int offset
    +Cursor before
    +Cursor after
  class Hotel {
  -UUID id
  +String name
  -Int objectid 
  GeoPoint *-- GeoPointType: Composition
  GeoPoint *-- GeographyPoint: Composition
  GeoPoint "1" <|-- "1" NearbyPoint: Implements
  NearbyPoints "1" -- "0..n"NearbyPoint: Contains
  Hotel "1" -- "1" GeoPoint: May Contain