Sitemap

Rendering Mermaid Diagrams with Svelte

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!

--

--

Terris Linenbach
Terris Linenbach

Written by Terris Linenbach

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

No responses yet