bootstrap modal close on form submit in react
You can close a Bootstrap modal on form submit in React by using JavaScript. You can add an event listener to the form submit event and call the hide
method on the Bootstrap modal instance to close it. Here's an example code snippet:
import React, { useRef } from "react";
import { Modal } from "bootstrap";
const MyModal = () => {
const modalRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
// Close the modal
const modal = new Modal(modalRef.current);
modal.hide();
// Additional form submit logic
// ...
};
return (
<div>
<button type="button" data-bs-toggle="modal" data-bs-target="#myModal">
Open Modal
</button>
<div className="modal" ref={modalRef} id="myModal">
<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" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
<form onSubmit={handleSubmit}>
{/ Form fields /}
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
);
};
export default MyModal;
In this example, we use the useRef
hook to create a reference to the modal element. We then add an event listener to the form's submit event and call the hide
method on the Bootstrap modal instance to close it.