I need to build a modal component that is opened from a parent component and closed from the modal component itself in React.
I’m setting the state in the parent component and passed it down to the child modal component as props:
const [modalIsOpen, setModalIsOpen] = useState(false)
const handleOpenFromParent = () => {
setModalIsOpen(true)
}
const handleCloseFromChild = () => {
setModalIsOpen(false)
}
and
<div
className={`${styles.w_30} p-3 d-flex justify-content-center align-items-center flex-column`}
onClick={handleOpenFromParent}
>
<ModalPaymentMethods
playerNickname={nickname}
paymentDescription={paymentMethodsVisa}
paymentLogo={<Icon icon='mdi:credit-card-outline' color={'#84c3d3'} style={{ fontSize: '150px' }} />}
depositTimes={11}
depositAmount={'€18.6k'}
depositTimesLastSixMonths={9}
depositQuantityLastSixMonths={'€12.7k'}
paymentMethodNumber={4301165517084005}
expiryMonth={'07'}
expiryYear={'2017'}
holderName={`${name + ' ' + lastName}`}
billingAddress={address}
modalIsOpen={modalIsOpen}
handleCloseFromChild={handleCloseFromChild}
/>
</div>
I have no problems in opening the modal from the parent, but I’m not managing to close it once opened, from the child component.
I’m passing a callback handleCloseFromChild
as a prop to set the visibility state back to false on the modal but it’s not working, modalIsOpen
remains always true and is never set to false from the callback function:
const ModalPaymentMethods = ({
playerNickname,
paymentDescription,
paymentLogo,
depositTimes,
depositAmount,
depositTimesLastSixMonths,
depositQuantityLastSixMonths,
paymentMethodNumber,
expiryMonth,
expiryYear,
holderName,
billingAddress,
modalIsOpen,
handleCloseFromChild
}) => {
console.log(modalIsOpen)
console.log(handleCloseFromChild)
return (
<div className={styles.ModalPaymentMethods}>
<Modal
open={modalIsOpen}
onClose={handleCloseFromChild}
aria-labelledby='modal-modal-title'
aria-describedby='modal-modal-description'
>
test
</Modal>
</div>
)
2
Answers
You should define a open state like this:
const [open,setOpen]=useState(false)
After that define a function to handle it:
const handleToggleModal=()=>{setOpen((current)=>!current)}
and you should pass this
handleToggleModal
function as props to the child component and call it everywhere you need to close the modal.open
state is used as a toggle boolean value to close and open the modalThe reason is that
ModalPaymentMethods
component inside the div element which hasonClick
event.Just try write console log on both
handleOpenFromParent
andhandleCloseFromChild
function, then you can find the problem.You can simply solve that problem by using
stopPropagation
method.