how to render a mermaid diagram inside a popup

22 views Asked by At

This is my App.js code in react

import React, { useState } from "react";
import Button from "@mui/material/Button";
import Modal from "@mui/material/Modal";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import mermaid from "mermaid";

mermaid.initialize({ startOnLoad: true });

export default function Popup() {
  const [open, setOpen] = useState(false);
  

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const children = `sequenceDiagram
    Alice->>John: Hello John, how are you?
    John-->>Alice: Great!
    Alice-)John: See you later!
  `;

  React.useEffect(() => {
    if (open) {
      mermaid.contentLoaded();
    }
  }, [open]);

  return (
    <div>
      <Button variant="contained" onClick={handleClickOpen}>
        Open Modal
      </Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box
          sx={{
            height: "90%",
            width: "90%",
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            bgcolor: "background.paper",
            border: "2px solid #000",
            boxShadow: 24,
            p: 4
          }}
        >
          <Typography id="modal-modal-title" variant="h6" component="h2">
            Mermaid Diagram
          </Typography>
          <Typography id="modal-modal-description" sx={{ mt: 2 }}>
            <div className="mermaid" style={{ height: "70%", width: "70%" }}>
              {children}
            </div>
          </Typography>
        </Box>
      </Modal>
    </div>
  );
}

What i am trying to do is , on click of a button, i want to open a modal popup and i want to render the script inside modal. but initially when the modal opens, it is displaying the script as a string, and when it re-renders with the modal in open state, then it is rendering the script. But my case is when the modal opens first time, at that time itself i want to render the script.How to achieve that?

0

There are 0 answers