Rendering Mermaid Diagrams with Svelte

Terris Linenbach
1 min readMay 15, 2023

Mermaid Logo

Svelte delivers a delightful low-code DX for responsive web applications.

This takes about a minute to load. Change the text on the right and watch the graphical diagram change! Click on the left panel to view the whole project. View on StackBlitz.

Here’s a brief overview of the pertinent code (view on StackBlitz):

<script>
import mermaid from 'mermaid';

// The default diagram
let diagram = `\
erDiagram
CUSTOMER }|..|{ DELIVERY-ADDRESS : has
CUSTOMER ||--o{ ORDER : places
CUSTOMER ||--o{ INVOICE : "liable for"
DELIVERY-ADDRESS ||--o{ ORDER : receives
INVOICE ||--|{ ORDER : covers
ORDER ||--|{ ORDER-ITEM : includes
PRODUCT-CATEGORY ||--|{ PRODUCT : contains
PRODUCT ||--o{ ORDER-ITEM : "ordered in"`
;

let container;

async function renderDiagram() {
const {svg} = await mermaid.render('mermaid', diagram)
container.innerHTML=svg;
}

$: diagram && renderDiagram()
</script>

<main>
<pre
contenteditable="true"
bind:innerHTML={diagram}
>
</pre>
<span bind:this={container}>
</main>
  • The function renderDiagram() renders the Mermaid diagram
  • The contents of the <pre> block are bound to the JavaScript variable ‘diagram’
  • Whenever the ‘diagram’ variable changes and is not empty, renderDiagram() is called. This is accomplished via:
$: diagram && renderDiagram()

Would you prefer to run Elixir on the backend? This Svelte component also runs on Phoenix. Check it out!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Terris Linenbach
Terris Linenbach

Written by Terris Linenbach

He/him. Coder since 1980. Always seeking the Best Way. CV: https://terris.com/cv

No responses yet

What are your thoughts?