I have simulate my issue in codesandbox: https://codesandbox.io/s/trusting-babbage-ovj2we?file=/src/App.js
I have create a nested modal, when the parent modal is opened, there is a button lead to the child modal. I have passed the useState
of the parent modal to the child modal as a prop, I want to close the parent model when the child modal is opened, however, both die when the button was clicked.
I have reviewed my code many times but have no idea what is causing this.
You can't do this, if the parent modal dies child will also die but you can do this by not wrapping the child modal inside the parent modal see below working code for your question
import * as React from "react";
import Box from "@mui/material/Box";
import Modal from "@mui/material/Modal";
import Button from "@mui/material/Button";
const style = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: "background.paper",
border: "2px solid #000",
boxShadow: 24,
pt: 2,
px: 4,
pb: 3
};
export default function NestedModal() {
const [open, setOpen] = React.useState(false);
const [openChild, setChildOpen] = React.useState(false);
const toggleOpenParent = () => {
setOpen(!open);
};
const toggleChild = () => {
setChildOpen(!openChild);
};
return (
<div>
<Button onClick={toggleOpenParent}>Open modal</Button>
<Modal open={open} onClose={toggleOpenParent}>
<Box sx={{ ...style, width: 400 }}>
<Button
onClick={() => {
toggleChild();
toggleOpenParent()
}}
>
Open Child Modal
</Button>
</Box>
</Modal>
<React.Fragment>
<Modal hideBackdrop open={openChild} onClose={toggleChild}>
<Box sx={{ ...style, width: 200 }}>
<Button onClick={toggleChild}>Close Child Modal</Button>
</Box>
</Modal>
</React.Fragment>
</div>
);
}