Reputation: 1245
I am creating a custom modal functionality where i need to close the modal after data submission is successful. I am able to pass simple function as props but if i try to pass with a callback, it returns an error. The error returned here: ParentComponent.js: Uncaught TypeError: cb is not a function
My code
import React, { useState } from 'react';
import Modal from 'react-bootstrap/Modal';
import Button from 'react-bootstrap/Button';
function CustomModal({btnVariant, btnClass, btnTxt, modalTitle, children, handleSave}) {
const [show, setShow] = useState(false);
const handleShow = () => setShow(true);
const handleClose = () => setShow(false);
const localHandleSave = (e) => {
handleSave(e, (err) => {
console.log('i am called back');
//handleClose() //here i will close it after the submission was successful
});
};
return (
<>
<Button variant={btnVariant} className={btnClass} onClick={handleShow}>
{btnTxt}
</Button>
<Modal show={show} backdrop="static" keyboard={false} size="lg" onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>{modalTitle}</Modal.Title>
</Modal.Header>
<Modal.Body>
{children}
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose}>
Close
</Button>
<Button variant="primary" onClick={(event) => localHandleSave(event)}>
Save
</Button>
</Modal.Footer>
</Modal>
</>
);
}
export default CustomModal;
Parent component
import CustomModal from './../../components/customModal/CustomModal';
import styles from './parentComponent.module.css';
function ParentComponent() {
const onSubmit = (e, cb) => {
//after api request is successfull...
cb(null);
};
return (
<div>
<CustomModal btnVariant="info" btnClass={styles.pull__right} btnTxt="+ Add" modalTitle="Add data" handleSave={onSubmit} />
</div>
); }
export default ParentComponent;
Upvotes: 3
Views: 5448
Reputation: 517
from your comment reply what you want to do is to make the child invisible, then you don't need a callback, just define a state variable, and switch to not showing the child component:
import React, { useState } from 'react';
import CustomModal from './../../components/customModal/CustomModal';
import styles from './parentComponent.module.css';
function ParentComponent() {
const [isShowCM, setIsShowCM] = useStatus(true);
const onSubmit = (e) => {
//after api request is successfull...
setIsShowCM(false);
};
return (
<div>
{isShowCM ? (
<CustomModal btnVariant="info" btnClass={styles.pull__right} btnTxt="+ Add" modalTitle="Add data" handleSave={onSubmit} />
) : null}
</div>
); }
export default ParentComponent;
Upvotes: 1