I am using the Modal Component from React Bootstrap Everything works as expected, except from the fact that I cannot figure out how to auto close the Modal after a successful submit.
I know I am able to call the onHide fuction from the Modal component like this at button click:
<Button onClick={props.onHide}>Close</Button>
Is there a way to auto call this onHide function if, and only if there is a successful submit form the MailingListSendgrid component?
index.js
<ModalMailingList show={modalShow} onHide={() => setModalShow(false)} />
ModalMailingList.js
import Modal from "react-bootstrap/Modal";
import MailingListSendgrid from "@/components/MailingListSendgrid";
export default function ModalMailingList(props) {
return (
<Modal
{...props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
className="special_modal" //Add class name here
>
<Modal.Header closeButton></Modal.Header>
<Modal.Body>
<MailingListSendgrid />
</Modal.Body>
</Modal>
);
}
MailingListSendgrid.js
.
.
.
.
const MailingListSendgrid = () => {
const [isError, setIsError] = useState(true);
const [shakeIt, setshakeIt] = useState(false);
const [mail, setMail] = useState("");
const [isLoading, setLoading] = useState(false);
const [message, setMessage] = useState(null);
const subscribe = () => {
const regEx = /[a-zA-Z0-9._% -] @[a-z0-9.-] \.[a-z]{2,8}(.[a-z{2,8}])?/g;
setMail("");
if (!regEx.test(mail) && mail !== "") {
setIsError(true);
setshakeIt(true);
setMessage("Email is Not Valid");
setTimeout(() => {
setshakeIt(false);
}, 1000);
} else if (mail === "") {
setIsError(true);
setshakeIt(true);
setMessage("Email is Empty");
setTimeout(() => {
setshakeIt(false);
}, 1000);
} else {
setLoading(true);
axios
.put("api/MailingList", {
mail,
})
.then((result) => {
if (result.status === 200) {
setIsError(false);
setMessage(result.data.message);
setLoading(false);
}
})
.catch((err) => {
setIsError(true);
setMessage(err.data.message);
setLoading(false);
});
setMessage(null);
setshakeIt(false);
}
};
return (
.
.
.
<input
onChange={(e) => {
setMail(e.target.value);
}}
type="email"
className={`form-control required email w-auto text-center text-sm-start`}
placeholder={subscription.formPlaceholder}
value={mail}
autoComplete="email"
required
></input>
<button
type="submit"
name="subscribe"
onClick={subscribe}
className="input-group-text justify-content-center"
disabled={isLoading}
>
.
.
.
);
};
export default MailingListSendgrid;
CodePudding user response:
I think that the best option here is to pass a function as a prop, thus still making the MailingListSendgrid reusable e.g.
<MailingListSendgrid onSubmit={()=> props.onHide()} />
And just use that in MailingListSendgrid
if it was successfull.