Mermaid JS: Render Diagrams in HTML and React (2026)
November 11, 2026 · 11 min read
Mermaid JS: Render Diagrams in a Web Page or App
Mermaid JS is the JavaScript library that turns text definitions into SVG diagrams in the browser. To use it, import it from a CDN or npm, add a pre element with the class mermaid, and it renders on page load. This guide covers plain HTML, bundlers and React, plus the version 12 and security settings that trip people up.
What Is Mermaid JS Code?
Mermaid code is plain text that describes a diagram, such as flowchart LR followed by lines like A --> B. The library parses that text and draws an SVG. It's MIT licensed, documented at mermaid.js.org and developed in the mermaid-js/mermaid repository on GitHub.
This post is about wiring up the library, not writing diagrams. For flowchart, sequence and Gantt syntax, plus where Mermaid works inside Markdown, read our guide to Mermaid diagrams in Markdown.
Here's the smallest working page. Save it as an HTML file and open it in a browser.
<!doctype html>
<html lang="en">
<body>
<pre class="mermaid">
flowchart LR
A[Write text] --> B[Mermaid parses it] --> C[SVG on the page]
</pre>
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@12/dist/mermaid.esm.min.mjs';
mermaid.initialize({ startOnLoad: true });
</script>
</body>
</html>
When the page finishes loading, Mermaid finds every element with class="mermaid", reads its text and swaps it for an SVG. You get three boxes joined by two arrows. The mermaid@12 path pins the major version, so a future version 13 can't change your diagrams overnight.
Install Mermaid JS from npm for a Bundler
For an app built with Vite, webpack or a similar bundler, install the package instead of loading a CDN file.
npm install mermaid
import mermaid from 'mermaid';
mermaid.initialize({ startOnLoad: false });
Version 12 declares Node.js 22.12 or later in its package.json, so an older Node can complain during install. The 12.0.0 changelog explains that this is mostly about dependencies, because Mermaid itself needs a browser to draw anything.
Import the bare mermaid package name, not a file path. The changelog warns that dist/mermaid.esm.min.mjs now contains syntax that Vite's module lexer rejects. Importing the package resolves to a different build and avoids the error. The published bundles target ES2024 and Safari 17.4 or later, so older browsers may need a transpile step.
mermaid.initialize Options You'll Actually Set
mermaid.initialize() takes one config object that applies to every diagram on the page. Call it once, before anything renders. These are the keys most apps touch:
mermaid.initialize({
startOnLoad: false, // don't auto-render on window load
securityLevel: 'strict', // the default; see the security section below
theme: 'default', // built-in theme name
look: 'classic', // also 'neo' or 'handDrawn'
layout: 'dagre', // layout engine, such as 'dagre' or 'elk'
});
The theme key picks one of Mermaid's built-in color schemes. The theming page on mermaid.js.org lists the names and the variables you can override.
Order of precedence matters when a diagram ignores your settings. Front matter or an %%{init}%% directive inside a diagram beats initialize(), which beats the diagram type's own defaults. So if one chart stays stubbornly dark, check its source before you debug your config.
We prefer startOnLoad: false in any app with dynamic content. You then decide exactly when diagrams render: after data arrives, after fonts load or after a route change. Calling mermaid.run() yourself makes that moment explicit.
Rendering Diagrams Added After Page Load with mermaid.run
Here's a common bug report. The diagram works on the first page, then shows as raw text after you navigate in a single-page app. That's expected. Auto-rendering fires once, on load, and never sees elements you add later.
The fix is mermaid.run(), which the usage docs call the preferred method for complex integrations. It's async and accepts a selector or a list of nodes:
mermaid.initialize({ startOnLoad: false });
// After your route or component inserts new diagrams:
await mermaid.run({ querySelector: '.mermaid' });
// Or render specific elements only:
await mermaid.run({ nodes: document.querySelectorAll('.new-diagram') });
A broken diagram doesn't stop the rest of the batch from rendering, but run() still rejects with its error at the end. Add suppressErrors: true to the options and it logs the error instead. Mermaid marks each processed element, so a second run() call skips diagrams it has already drawn. The older mermaid.init() has been deprecated since version 10, so replace it if you find it in legacy code.
If your diagrams come from Markdown, your parser usually outputs fenced mermaid blocks as pre and code tags. Turn those into pre class="mermaid" elements holding the raw text, then call run(). Our markdown-it and marked guide covers the parser side.
The flowchart below sums up both rendering paths.
Our preview draws Mermaid fences in the browser, but it doesn't run your page's JavaScript, so your initialize() settings don't apply there. Use it to check syntax, then confirm the final look in your own page.
Using mermaid.render to Get an SVG String
Sometimes you want the SVG itself, not a replaced element. mermaid.render() takes a unique ID and the diagram text, and resolves to an object with svg and bindFunctions:
const text = 'flowchart TD\n Start --> Stop';
const { svg, bindFunctions } = await mermaid.render('diagram-1', text);
const container = document.getElementById('output');
container.innerHTML = svg;
bindFunctions?.(container); // attaches click handlers, if the diagram has any
The ID becomes the SVG's own id, so give each call a fresh one. Two diagrams sharing an ID can end up sharing styles in odd ways. Call bindFunctions only after the SVG is in the DOM, since it wires up events on live elements.
This is the API to reach for when you cache rendered output, show a preview beside a textarea, or let users download the result.
For a live preview, don't render on every keystroke. Wait until typing pauses for a few hundred milliseconds, then call mermaid.parse() and render only when it succeeds. A half-typed arrow otherwise flashes a syntax error on almost every key press, which feels broken even when it isn't.
How Do You Use Mermaid JS in React?
The core mermaid package doesn't ship a React component, but a small wrapper around render() covers most needs. This one loads Mermaid with a dynamic import on first use and initializes it once, so the library stays out of server rendering and your main bundle:
import { useEffect, useRef } from 'react';
let counter = 0;
let loading = null;
function loadMermaid() {
loading ??= import('mermaid').then(({ default: mermaid }) => {
mermaid.initialize({ startOnLoad: false });
return mermaid;
});
return loading;
}
export function MermaidDiagram({ chart }) {
const ref = useRef(null);
useEffect(() => {
let cancelled = false;
(async () => {
const mermaid = await loadMermaid();
if (!(await mermaid.parse(chart, { suppressErrors: true }))) {
if (!cancelled && ref.current) ref.current.textContent = 'Invalid diagram';
return;
}
const { svg, bindFunctions } = await mermaid.render(`mermaid-${++counter}`, chart);
if (cancelled || !ref.current) return;
ref.current.innerHTML = svg;
bindFunctions?.(ref.current);
})();
return () => { cancelled = true; };
}, [chart]);
return <div ref={ref} />;
}
Use it as <MermaidDiagram chart={source} />. The cancelled flag stops a slow, stale render from overwriting a newer one when chart changes quickly. The counter gives every render a plain, unique ID that's always valid in a CSS selector.
If you render Markdown with react-markdown, a custom code component can hand mermaid blocks to this wrapper. Our React Markdown guide shows how custom components plug in.
How Can You Save a Mermaid Diagram as an Image?
In the browser, the SVG string from render() is already an image file. Wrap it in a Blob and offer a download:
const { svg } = await mermaid.render('export-1', text);
const blob = new Blob([svg], { type: 'image/svg+xml' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'diagram.svg';
link.click();
For builds and CI, the official mermaid-cli package gives you an mmdc command:
npm install -g @mermaid-js/mermaid-cli
mmdc -i diagram.mmd -o diagram.svg
mmdc -i diagram.mmd -o diagram.png -t dark -b transparent
The first command writes an SVG. The second writes a PNG with the dark theme and a transparent background. A Docker image, minlag/mermaid-cli, works when you can't install Node globally. Our Mermaid to PNG guide covers the scale and size flags for sharper images.
For a one-off export with no code at all, our Mermaid editor runs in the browser, shows a live preview with templates and themes, and exports PNG or SVG.
Fixing Mermaid JS Rendering Errors and Version 12 Surprises
Most problems fall into a few patterns, and each has a quick check.
- The diagram shows as raw text. You set
startOnLoad: falseand never calledrun(), or the script tag is missingtype="module"for the ESM import. - A syntax error breaks the page. Validate first with
await mermaid.parse(text, { suppressErrors: true }). It returns an object withdiagramTypewhen the text is valid andfalsewhen it isn't, instead of throwing. - Labels spill outside their boxes. Mermaid measured text before your web font loaded. The docs advise waiting until the page and its fonts finish loading before you render. If your body font leaks into labels, set a font on
pre.mermaidexplicitly. - Click handlers do nothing. The default
securityLevelisstrict, which encodes HTML in labels and disables clicks. Switching tolooseturns them back on.
Make that switch only for diagrams you wrote yourself. loose enables clicks and HTML labels, antiscript does the same but strips script tags, and sandbox renders inside a sandboxed iframe. Keep strict whenever users can submit diagram text, because the docs say the looser levels are for when you take responsibility for the diagram source.
Version 12 also changed how existing diagrams look. According to the changelog, flowchart, sequence, class, state, ER and several other types now default to the redux-color theme and the neo look. Many of them also lay out with ELK instead of dagre. To get the old appearance back, set theme: 'default', look: 'classic' and layout: 'dagre' in initialize().
One limitation to plan around: Mermaid needs a real browser to measure and draw text. There's no pure Node.js renderer in the core package. Server-side rendering goes through mmdc, which drives a headless Chromium through Puppeteer, so it's slower and heavier than a typical build step.
Mermaid JS comes down to three calls: initialize() once, run() for elements on the page, and render() when you need the SVG string. Pin the major version, keep securityLevel strict for user content, and set the classic theme and look if version 12 surprised you. To sketch a diagram before wiring it into your app, paste a fenced mermaid block into the editor and watch the preview draw it.