简体   繁体   中英

How can I use useState Reactjs to control open or close a Modal Bootstrap? (not use ReactBootstrap library)

I am working with Bootstrap modal and Reactjs. Now I want to control how to open and close a Bootstrap Modal without Jquery code. So my idea is using useState to control state of modal, if true it will add class "show" to open modal and false it add class "hide". But it not work, How can I solve this? Or are there anyway to control modal without Jquery code? Thanks

const [openModal, setopenModal] = useState(false);
const openmodal = () => {
   setopenModal(!openModal);
};
return (
 <div>
  <button onClick={openmodal}>open</button>
   <div id="mod" className={`modal ${openModal ? 'show' : 'hide'}`}>
    <div className="modal-dialog modal-xl">
      <div className="modal-content">
        hello
      </div>
    </div>
  </div>
</div>

You could use the data attributes.

Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as in data-show="".

The data-show attribute specifies whether to show the modal when initialized.

<div id="mod" data-show={openModal ? 'true' : 'false'}> ... </div>

See: https://www.w3schools.com/Bootstrap/bootstrap_ref_js_modal.asp

Alternatively you could use useRef to get the modal DOM element and access it.

function model(){ const [openModal, setopenModal] = useState(false); const openmodal = () => { setopenModal(state=>!state); }; return ( <div> <button onClick={openmodal}>open</button> <div id="mod" className={`modal ${openModal ? 'show' : 'hide'}`}> <div className="modal-dialog modal-xl"> <div className="modal-content"> hello </div> </div> </div> </div> ) }

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