简体   繁体   中英

Triggering a Bootstrap Modal in React without npm react-bootstrap

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: :-)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM