Today, I am facing an issue with hiding the Bootstrap5 modal in a TypeScript function. Despite trying to invoke the hide function on the modal element, it does not work as expected. Here is the minimal code snippet to reproduce this problem:
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import * as bootstrap from 'bootstrap';
const App: React.FC = () => {
const handleModal = (show: boolean, modalId: string) => {
let modal = document.getElementById(modalId);
if (modal) {
var myModal = new bootstrap.Modal(modal);
show ? myModal.show() : myModal.hide();
myModal.hide();
}
}
return (
<div>
<button onClick={() => { handleModal(true, "deleteFileModal") }}>show</button>
<div>
<div className="modal fade" id="deleteFileModal" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="deleteModalLabel">Title</h5>
<button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
...
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" className="btn btn-primary" >Confirm</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default App;
Despite calling the modal hide function at the end, the modal still did not hide properly. What am I missing here? How can I resolve this issue? In my project, the hide method is used like this:
const handleOk = () => {
let params = {
name: createFileName,
project_id: pid,
parent: pid,
file_type: 1
};
addFile(params).then((resp) => {
if (ResponseHandler.responseSuccess(resp)) {
handleModal(false,"createFileModal");
getFileList(pid?.toString());
}
});
};
The modal handling function is defined as follows:
const handleModal = (show: boolean, modalId: string) => {
let modal = document.getElementById(modalId);
if (modal) {
var myModal = new bootstrap.Modal(modal);
show ? myModal.show() : myModal.hide();
}
}
Unfortunately, the modal closure is not successful.