npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-x-mermaid

v0.0.10

Published

A small, lightweight React wrapper component and hook for rendering Mermaid diagrams from Mermaid syntax strings.

Downloads

421

Readme

React x Mermaid

A small, lightweight React wrapper component and hook for rendering Mermaid diagrams from Mermaid syntax strings.

This package exposes a React component and a hook so you can render and control Mermaid diagrams in React apps with minimal setup.

Features

  • Simple Mermaid React component that accepts a Mermaid diagram string.
  • useMermaid hook for programmatic control and rendering.
  • Supports server-friendly build output (CJS + ESM + types).

Installation

Install from npm:

npm install react-x-mermaid mermaid
# or
yarn add react-x-mermaid mermaid

Peer dependencies:

Quick Start

Render a diagram using the Mermaid component:

import "./App.css";
import RenderMermaid from "react-x-mermaid";

function App() {
  const d1 = `
  graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
`;

  return (
    <div className="app">
      <RenderMermaid mermaidCode={d1} mermaidConfig={{ theme: "dark" }} />
    </div>
  );
}

export default App;

Or use the useMermaid hook for manual rendering and lifecycle control:

import { useMermaid } from "react-x-mermaid";

function AdvanceMermaidRenderer({ chart }: { chart: string }) {
  // hook also gives you svg along with ref and error which it generate which you can use to download and save locally if required
  const { ref, error } = useMermaid(chart, {
    theme: "dark", // mermaid config
  });

  if (error) {
    // show error or render code in <pre> and <code> tags if you need as a fallback.
    return <div className="mermaid__error">{error}</div>;
  }

  return <div className="mermaid-renderer" ref={ref} />;
}

export default AdvanceMermaidRenderer;
// App.tsx;

import "./App.css";
import AdvanceMermaidRenderer from "./AdvanceMermaidRenderer";

function App() {
  const d1 = `
  graph TD;
  A-->B;
  A-->C;
  B-->D;
  C-->D;
`;

  return (
    <div className="app">
      <AdvanceMermaidRenderer chart={d1} />
    </div>
  );
}

export default App;

API

useMermaid Hook

A React hook that provides programmatic control over Mermaid diagram rendering with error handling and lifecycle management.

Signature

useMermaid(chart: string, config?: MermaidConfig) => {
  ref: RefObject<HTMLDivElement | null>;
  svg: string;
  error: string | null;
}

Parameters

| Parameter | Type | Required | Description | | --------- | --------------- | -------- | ------------------------------------------------------------------- | | chart | string | Yes | The Mermaid diagram syntax string to render | | config | MermaidConfig | No | Optional Mermaid configuration object (defaults to internal config) |

Returns

| Property | Type | Description | | -------- | ----------------------------------- | ------------------------------------------------------------------------------------- | | ref | RefObject<HTMLDivElement \| null> | React ref to attach to a DOM element where the diagram will be rendered | | svg | string | The rendered SVG string of the diagram (useful for downloading or further processing) | | error | string \| null | Error message if diagram rendering fails, null if successful |

Usage Examples

Basic Usage:

import { useMermaid } from "react-x-mermaid";

function MyDiagram() {
  const chart = `
    graph TD;
    A-->B;
    A-->C;
    B-->D;
    C-->D;
  `;

  const { ref, svg, error } = useMermaid(chart);

  if (error) {
    return <div>Error: {error}</div>;
  }

  return <div ref={ref} />;
}

With Custom Configuration:

import { useMermaid } from "react-x-mermaid";

function ThemedDiagram() {
  const chart = "graph TD; A-->B;";

  const { ref, error } = useMermaid(chart, {
    theme: "dark",
    flowchart: {
      useMaxWidth: true,
      htmlLabels: true,
    },
  });

  return <div ref={ref} />;
}

Using SVG for Download:

import { useMermaid } from "react-x-mermaid";

function DownloadableDiagram() {
  const chart = "graph TD; A-->B;";
  const { ref, svg, error } = useMermaid(chart);

  const downloadSVG = () => {
    if (svg) {
      const blob = new Blob([svg], { type: "image/svg+xml" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "diagram.svg";
      a.click();
    }
  };

  return (
    <div>
      <div ref={ref} />
      {svg && <button onClick={downloadSVG}>Download SVG</button>}
    </div>
  );
}

Behavior

  • Automatic Re-rendering: The diagram automatically re-renders when the chart or config parameters change
  • Error Handling: Catches and exposes rendering errors through the error property
  • DOM Integration: Automatically injects the rendered SVG into the DOM element referenced by ref
  • Async Rendering: Uses Mermaid's async rendering API for better performance

Error Handling

The hook gracefully handles various error scenarios:

  • Invalid Mermaid syntax
  • Configuration errors
  • Rendering failures

When an error occurs, the error property contains the error message, and the svg property is cleared.

Mermaid Component

A React component that renders Mermaid diagrams with built-in error handling, copy functionality, and SVG download capabilities.

Signature

interface RenderMermaidProps {
  mermaidCode: string;
  errorComponent?: React.ComponentType<{ error: string; mermaidCode: string }>;
  disableDownload?: boolean;
  disableCopy?: boolean;
  downloadComponent?: React.ComponentType<{ onClick: () => void }>;
  copyComponent?: React.ComponentType<{ onClick: () => void }>;
  mermaidConfig?: MermaidConfig;
  renderCode?: React.ComponentType<{ code: string }>;
}

const Mermaid: React.FC<RenderMermaidProps> = (props) => JSX.Element;

Props

| Prop | Type | Required | Default | Description | | ------------------- | ------------------------------------------------------------- | -------- | ------- | ------------------------------------------------------------------------- | | mermaidCode | string | Yes | - | The Mermaid diagram syntax string to render | | errorComponent | React.ComponentType<{ error: string; mermaidCode: string }> | No | - | Custom component to render when diagram fails to load | | disableDownload | boolean | No | false | When true, hides the download SVG button | | disableCopy | boolean | No | false | When true, hides the copy code button | | downloadComponent | React.ComponentType<{ onClick: () => void }> | No | - | Custom component for the download button (replaces default button) | | copyComponent | React.ComponentType<{ onClick: () => void }> | No | - | Custom component for the copy button (replaces default button) | | mermaidConfig | MermaidConfig | No | - | Mermaid configuration object passed to mermaid.initialize() | | renderCode | React.ComponentType<{ code: string }> | No | - | Custom component for rendering the raw Mermaid code (used in error state) |

Features

  • Automatic Rendering: Renders Mermaid diagrams from syntax strings
  • Error Handling: Gracefully handles rendering errors with fallback UI
  • Copy Functionality: Built-in copy-to-clipboard for the Mermaid code
  • SVG Download: Download rendered diagrams as SVG files
  • Customizable UI: Replace default buttons and error components with custom ones
  • Memory Management: Properly cleans up resources on unmount
  • Memoized: Uses React.memo for performance optimization

Usage Examples

Basic Usage:

import Mermaid from "react-x-mermaid";

function App() {
  const diagram = `
    graph TD;
    A[Start] --> B{Decision};
    B -->|Yes| C[Action 1];
    B -->|No| D[Action 2];
    C --> E[End];
    D --> E;
  `;

  return <Mermaid mermaidCode={diagram} />;
}

With Custom Configuration:

import Mermaid from "react-x-mermaid";

function ThemedDiagram() {
  const diagram = "graph TD; A-->B;";

  return (
    <Mermaid
      mermaidCode={diagram}
      mermaidConfig={{
        theme: "dark",
        flowchart: {
          useMaxWidth: true,
          htmlLabels: true,
        },
      }}
    />
  );
}

With Disabled Actions:

import Mermaid from "react-x-mermaid";

function SimpleDiagram() {
  const diagram = "graph TD; A-->B;";

  return (
    <Mermaid mermaidCode={diagram} disableDownload={true} disableCopy={true} />
  );
}

With Custom Error Component:

import Mermaid from "react-x-mermaid";

function CustomErrorComponent({ error, mermaidCode }) {
  return (
    <div style={{ padding: "20px", border: "1px solid red" }}>
      <h3>Diagram Error</h3>
      <p>{error}</p>
      <details>
        <summary>View Code</summary>
        <pre>{mermaidCode}</pre>
      </details>
    </div>
  );
}

function DiagramWithCustomError() {
  const diagram = "invalid mermaid syntax";

  return (
    <Mermaid mermaidCode={diagram} errorComponent={CustomErrorComponent} />
  );
}

With Custom Action Buttons:

import Mermaid from "react-x-mermaid";

function CustomCopyButton({ onClick }) {
  return (
    <button onClick={onClick} style={{ background: "blue", color: "white" }}>
      📋 Copy Code
    </button>
  );
}

function CustomDownloadButton({ onClick }) {
  return (
    <button onClick={onClick} style={{ background: "green", color: "white" }}>
      💾 Download
    </button>
  );
}

function DiagramWithCustomButtons() {
  const diagram = "graph TD; A-->B;";

  return (
    <Mermaid
      mermaidCode={diagram}
      copyComponent={CustomCopyButton}
      downloadComponent={CustomDownloadButton}
    />
  );
}

With Custom Code Renderer:

import Mermaid from "react-x-mermaid";

function SyntaxHighlightedCode({ code }) {
  return (
    <div style={{ background: "#f5f5f5", padding: "10px" }}>
      <h4>Mermaid Code:</h4>
      <pre style={{ fontSize: "12px" }}>{code}</pre>
    </div>
  );
}

function DiagramWithCustomCodeRenderer() {
  const diagram = "graph TD; A-->B;";

  return <Mermaid mermaidCode={diagram} renderCode={SyntaxHighlightedCode} />;
}

CSS Classes

The component applies the following CSS classes that you can style:

  • .mermaid-renderer - Main container
  • .mermaid-actions - Container for action buttons
  • .mermaid-action-button - Default action buttons
  • .btn-copy - Copy button
  • .btn-download - Download button
  • .mermaid-diagram - Container for the rendered diagram
  • .mermaid-error-container - Error state container
  • .mermaid-code-renderer - Default code renderer

Behavior

  • Automatic Re-rendering: Re-renders when mermaidCode or mermaidConfig changes
  • Error Recovery: Shows error UI with code fallback when rendering fails
  • Memory Management: Cleans up SVG content on unmount to prevent memory leaks
  • Clipboard Integration: Uses navigator.clipboard.writeText() for copy functionality
  • File Download: Generates and downloads SVG files with proper MIME type

Contributing

Contributions are welcome. Please open issues or PRs for bugs and improvements. Keep changes small and add tests for new behavior.

License

MIT

Keywords react react-componentmuimaterial-uimaterial design