Search code examples
javascriptreactjstwitter-bootstrapcdn

unable to show modal instead code for modal shows on the bottom of the page


Please I have issues with showing a modal with bootstrap 5. I am not using react-bootstrap so I can't use state to toggle modal,I am using cdn with dom manipulation to show modal on a page. Instead of the modal showing the code turns up. enter image description here

This is the code

import React from "react";
import { Modal } from "bootstrap";

const editProduct = () => {
  let modalWrapper = null;
  modalWrapper = document.createElement(
    "div"
  ).innerHTML = `<div class="modal fade modal-dialog modal-dialog-scrollable" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Understood</button>
      </div>
    </div>
  </div>
</div>
`;
  document.body.append(modalWrapper);
  let modal = new Modal(modalWrapper.querySelector(".modal"));
  modal.show();
};

export default editProduct;

Help will be appreciated. Thanks


Solution

  • I had to yarn add bootstrap and then import 'bootstrap/dist/css/bootstrap.css'. Then import { Modal } from "bootstrap";. Then let modal = new Modal(document.querySelector(".modal")); Also I had to do this in two steps for it to work

      modalWrapper = document.createElement("div");
      modalWrapper.innerHTML = `.....`