How to create State diagram in MermaidJS

1. Install MermaidJS

You can install MermaidJS by including the MermaidJS library in your project or by installing it via npm.

npm i mermaid

2. Define the diagram

To create a state diagram, start the definition with stateDiagram-v2. Define each transition as StateA --> StateB : event, and use [*] to mark the start and end pseudostates.

stateDiagram-v2
    [*] --> Idle
    Idle --> Running : start
    Running --> Paused : pause
    Paused --> Running : resume
    Running --> [*] : finish
    Paused --> [*] : cancel

In this example, the machine starts in Idle, moves to Running on start, can toggle between Running and Paused, and reaches the end pseudostate on finish or cancel.

3. Transitions and pseudostates

MermaidJS state diagrams support a few core building blocks:

ElementSyntaxMeaningPreview
TransitionA --> B : eventMove from state A to state B when event occurs
Start state[*] --> AThe initial pseudostate the machine begins in
End stateA --> [*]The final pseudostate the machine terminates in
Choicestate check <<choice>>Branch to different states based on a condition

4. Composite (nested) states

A state can contain its own sub-diagram by wrapping it with state Name { ... }. The nested diagram has its own start pseudostate, scoped to the parent state.

stateDiagram-v2
    [*] --> Active
    state Active {
        [*] --> NumLockOff
        NumLockOff --> NumLockOn : EvNumLockPressed
        NumLockOn --> NumLockOff : EvNumLockPressed
    }
    Active --> [*]

5. Render the diagram

Once you have defined the diagram, you can render it on your webpage by including the MermaidJS library and calling the mermaid function with the diagram definition as a string. Here is an example of how to do this

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script>
      mermaid.initialize({
        startOnLoad: true
      });
    </script>
  </head>
  <body>
    <div class="mermaid">
      stateDiagram-v2
        [*] --> Idle
        Idle --> Running : start
        Running --> Paused : pause
        Paused --> Running : resume
        Running --> [*] : finish
        Paused --> [*] : cancel
    </div>
  </body>
</html>

You can use this MermaidJS Playground Link to explore that particular example.