'How to close Bootstrap 5 modal in React.js?
Using Bootstrap 5 Modal in React.js, the Modal opens on click of the button. If we have a form on the modal, need to perform some validations, and allow to submit the form on successful validation - we cannot use data-bs-dismiss="modal"
to submit button, as it closes the modal immediately.
Now, what is the best approach to close the modal on successful form submission?
Please provide a solution without using jQuery as it is removed from Bootstrap v5 and also not recommended to use alongside React.js.
Also, many have suggested NOT to use document.getElementByID or document.querySelector in React because of its Virtual DOM usage concept.
Update: Able to achieve it with a workaround solution by clicking the Close button after successful form submission, as shown below. But still looking for an ideal solution, if there is any.
In constructor, created a ref:
this.closeModalRef = React.createRef();
In render, added this ref for close button:
<button type="button" className="btn btn-secondary" data-bs-dismiss="modal" id='closeModal' ref={this.closeModalRef}>Close</button>
In submit handler, after successful form submission:
this.closeModalRef.current.click();
Solution 1:[1]
you can also try
document.getElementById('closeModal').click();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Satish Kumar sonker |