DEV Community

Cover image for Mermaid.js - Sketching diagrams using code
Mirza Leka
Mirza Leka

Posted on

Mermaid.js - Sketching diagrams using code

Mermaid.js is a text-based diagramming language that lets technical writers create and modify complex diagrams with simple code.

Example

Let's say you're making a family tree and want to visualize it with Mermaid.js:

:::mermaid
flowchart TD
A["Grandad"]
B["Dad"]
C["Me"]
:::
Enter fullscreen mode Exit fullscreen mode

What this does is:

  • tells Mermaid.js that you want to use a flowchart diagram
  • to create three separate entities (boxes) with labels on them

family-tree

Then add arrows to create a relationship between entities.

:::mermaid
flowchart TD
A["Grandad"]
--> B["Dad"]
B --> C["Me"]
:::
Enter fullscreen mode Exit fullscreen mode

family-tree-relationship

And there you go. But you can also apply different conditions (A => B or A => C):

:::mermaid
flowchart TD
A["Raining outside?"]
A --> |Yes| B["Take umbrella"]
A --> |No| C["Take sunglasses"]
:::
Enter fullscreen mode Exit fullscreen mode

flow-conditions

Mermaid supports a wide range of diagram types, including flowcharts, pie charts, sequence diagrams, UML diagrams, mind maps, etc, as well as colors and style kits for each.

I'm not going to go through each one of these because the official documentation is pretty detailed. I'm going to teach you how to use these diagrams today.

Where can I render the diagram?

You can preview Mermaid diagrams in any markdown file - GitHub repository, code editor of choice, or Notion.

GitHub markdown file

Create a markdown file in your GitHub repository and paste the snippet inside the code block:

:::mermaid
<YOUR-DIAGRAM-CODE>
:::
Enter fullscreen mode Exit fullscreen mode

Surround the code block with three backticks or three colons, followed by the text "mermaid".

Here is a GitHub gist snippet I created for this demonstration.

Visual Studio Code

Just like on GitHub, create a markdown file inside the project and write your Mermaid.js script. To preview the diagram, the VSC has a markdown preview extension you can install in your editor.

Then, right-click on the markdown file (you wish to preview), choose Open With, and then choose the Markdown preview extension you've installed. The markdown should appear in the preview window.

vsc-markdown-preview

Can I use AI?

It's actually one of my favorite things to do when I need to document a feature or when I'm getting started on a new project.

Just for reference, this is the original code that I gave to Claude Code:

[Route("api/[controller]")]
[ApiController]
public class GamesController(IGamesService _gamesService) : ControllerBase
{

    [Route("NewGameMode")]
    [HttpPost]
    public async Task<ActionResult<GetGameModeDTO>> NewGameMode([FromBody] CreateGameModeDTO dto)
    {
        try
        {
            return await _gamesService.CreateGameMode(dto);
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
    public async Task<GetGameModeDTO> CreateGameMode(CreateGameModeDTO gameMode)
    {
        var newGameMode = new GameModes
        {
            Title = gameMode.Title,
            ShortTitle = gameMode.ShortTitle,
            GameType = gameMode.GameType
        };

        _gamesContext.GameModes.Add(newGameMode);
        await _gamesContext.SaveChangesAsync();

        var mappedGameMode = GetGameModeDTO.ToResponse(newGameMode);
        return mappedGameMode;
    }
Enter fullscreen mode Exit fullscreen mode
public class GetGameModeDTO
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string ShortTitle { get; set; }

    public static GetGameModeDTO ToResponse(GameModes gameMode)
    {
        return new GetGameModeDTO()
        {
            ID = gameMode.ID,
            Title = gameMode.Title,
            ShortTitle = gameMode.ShortTitle
        };
    }

}
Enter fullscreen mode Exit fullscreen mode

Now, Open Claude (or your LLM agent of choice) and ask it to analyze the project:

Hey Claude, analyze this project for me and summarize the language used, classes and core functionalities.
Enter fullscreen mode Exit fullscreen mode

Then ask it to draw you a map:

Claude, can you describe what's going on from the games controller to the database using a Mermaid.js sequence diagram in the README.md?
Enter fullscreen mode Exit fullscreen mode

And the output is a Mermaid.js diagram

:::mermaid
sequenceDiagram
    participant Client
    participant GamesController
    participant GamesService
    participant GamesContext
    participant SQL as SQL Server (Game_Modes)

    Client->>GamesController: POST /api/games/NewGameMode β€” { title, shortTitle, gameType }
    GamesController->>GamesService: CreateGameMode(CreateGameModeDTO)
    GamesService->>GamesService: new GameModes { Title, ShortTitle, GameType }
    GamesService->>GamesContext: GameModes.Add(newGameMode)
    GamesService->>GamesContext: SaveChangesAsync()
    GamesContext->>SQL: INSERT INTO Game_Modes (Title, Short_Title, Game_Type) VALUES (...)
    SQL-->>GamesContext: auto-generated ID
    GamesContext-->>GamesService: entity with new ID populated
    GamesService->>GamesService: GetGameModeDTO.ToResponse(entity)
    GamesService-->>GamesController: GetGameModeDTO
    GamesController-->>Client: 200 OK β€” { id, title, shortTitle }
:::
Enter fullscreen mode Exit fullscreen mode

That you can preview in the markdown file.

mermaid-sequence-diagram

Pretty neat, right? Much faster than drawing manually.
Here's another example of asking Claude to do my homework.

mermaidjs-flow-chart

Summary

Mermaid.js is a pretty powerful tool when you need to sketch out functionalities to analyze or demonstrate. For more on Mermaid.js, feel free to visit the official documentation.

Until next time πŸ‘‹

Top comments (0)