Home > Mobile >  Triggering a Bootstrap Modal in React without npm react-bootstrap
Triggering a Bootstrap Modal in React without npm react-bootstrap

Time:08-11

I try to code a Modal in React.js using Bootstrap5 but I can not use npm react-bootstrap out of several reasons. I tryd an approach where I use state to set Modal classes with a button which worked with my NavBar as well, but it does not work for my modal.

import React, { useState } from "react";

const Modal = (props) => {
  const [modalTriggered, setModalTriggered] = useState(true);

  const handleModalTrigger = () => setModalTriggered(!modalTriggered);

  return (
    <React.Fragment>
      <button
        onClick={handleModalTrigger}
        aria-expanded={!modalTriggered ? true : false}
        className="btn btn-primary"
      >
        Trigger modal
      </button>

      <div>
        <div className={`modal ${modalTriggered ? "hide" : "show"}`}>
          <div className="modal-dialog">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title">Modal title</h5>
                <button type="button" className="btn-close"></button>
              </div>
              <div className="modal-body">
                <p>Modal body text goes here.</p>
              </div>
              <div className="modal-footer">
                <button
                  type="button"
                  className="btn btn-secondary"
                  data-bs-dismiss="modal"
                >
                  Close
                </button>
                <button type="button" className="btn btn-primary">
                  Save changes
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
};

export default Modal;

I've learned from Bootstraps dodumentation that "hide" or "show" classes are used to trigger the Modal but the only thing happening is my button which changes "aria-expanded" when clicked. Hope one of you has an idea what I'm doing wrong, thanks in regard! :-)

CodePudding user response:

You can trigger the Modal by set the "display" value instead of pass it to className directly. Bascially, replace

 <div className={`modal ${modalTriggered ? "hide" : "show"}`}>

by

<div style={{ display: modalTriggered ? 'block' : 'none' }}>

will fix your issue

  • Related