1

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

timo.js
  • 72
  • 1
  • 7

1 Answers1

1

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

Yen Nguyen
  • 104
  • 4
  • But where would I pass modal class and fade in your solution? – timo.js Aug 11 '22 at 13:49
  • You can pass in anything you want if you make them Modal's props. Let's say you want to pass in the flag to trigger the Modal and an extra class, then it should be some think like this: – Yen Nguyen Aug 11 '22 at 14:06
  • but if i add class="modal fade" my modal isn't visible, but not hidden either. I can't see it, but I can't click on the Background either, you have any idea? – timo.js Aug 16 '22 at 09:30