How to replace the existing mermaid script with a new one onclick

23 Views Asked by At

I am trying to replace the existing mermaid script with a new one when someone clicks on it.This is my code I am showing a script diagram in the UI and when a click happens on it trying to show a new diagram. mermaid version i am using is ^10.7.0

import React from "react";
import mermaid from "mermaid";
import "./App.css";

mermaid.initialize({
  startOnLoad: true,
  theme: "default",
  securityLevel: "loose",
  themeCSS: `
    g.classGroup rect {
      fill: #282a36;
      stroke: #6272a4;
    } 
    g.classGroup text {
      fill: #f8f8f2;
    }
    g.classGroup line {
      stroke: #f8f8f2;
      stroke-width: 0.5;
    }
    .classLabel .box {
      stroke: #21222c;
      stroke-width: 3;
      fill: #21222c;
      opacity: 1;
    }
    .classLabel .label {
      fill: #f1fa8c;
    }
    .relation {
      stroke: #ff79c6;
      stroke-width: 1;
    }
    #compositionStart, #compositionEnd {
      fill: #bd93f9;
      stroke: #bd93f9;
      stroke-width: 1;
    }
    #aggregationEnd, #aggregationStart {
      fill: #21222c;
      stroke: #50fa7b;
      stroke-width: 1;
    }
    #dependencyStart, #dependencyEnd {
      fill: #00bcd4;
      stroke: #00bcd4;
      stroke-width: 1;
    } 
    #extensionStart, #extensionEnd {
      fill: #f8f8f2;
      stroke: #f8f8f2;
      stroke-width: 1;
    }`,
  fontFamily: "Fira Code"
});

export default class App extends React.Component {
  state = {
    mermaidScript: `
      sequenceDiagram
      Alice ->> Bob: Hello Bob, how are you?
      Bob-->>John: How about you John?
    `
  };

  componentDidUpdate() {
    mermaid.render("mermaid", this.state.mermaidScript, (svgCode) => {
      document.getElementById("mermaid").innerHTML = svgCode;
    });
  }

  handleClick = () => {
    this.setState({
      mermaidScript: `
        sequenceDiagram
        Alice ->> Bob: Hello Bob, how are you?
        Bob-->>John: How about you John?
        Bob--x Alice: I am good thanks!
        Bob-x John: I am good thanks!
        Note right of John: Bob thinks a long<br/>long time, so long<br/>that the text does<br/>not fit on a row.
        Bob-->Alice: Checking with John...
        Alice->John: Yes... John, how are you?
      `
    });
  };

  render() {
    return (
      <div id="mermaid" onClick={this.handleClick}>
        {this.state.mermaidScript}
      </div>
    );
  }
}

It is getting replaced but the new script is coming as a text in the uI. Diagram is not coming.How to re-render or re-run it again

0

There are 0 best solutions below