Home > Mobile >  How can I prevent the modal window from closing in React?
How can I prevent the modal window from closing in React?

Time:08-18

I made a modal window in React. I created a state called modalbool and made the modal window appear when modalbool is true. And I created a parent component called Backdrop and closed the modal window when I clicked the Background. However, even if I click the ModalContainer component, which is a child component, modalClosefunc is executed and the modal window is closed. How can I make modalbool become false and close the modal window when only the Backdrop component is pressed?

this is my code

const Backdrop = styled.div`
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top:0;
left: 0;
background-color: rgba(0,0,0,0.7);
width: 100vw;
height: 100vh;
`

const ModalContainer = styled.div`
position: relative;
width: 700px;
height: 600px;
background-color: lightcoral;

`;

const [modalbool, setModalbool] = useState(false);



  {modalbool ? (
    <Backdrop onClick={modalClosefunc}>
    <ModalContainer>

    </ModalContainer>
</Backdrop>
      ) : null

CodePudding user response:

Add a click event to ModalContainer for stopPropagation

CodePudding user response:

Quick and hacky workaround is to adjust the z-index for the css of the components. If modalbool is true, set the z-index of the modal to some high number and reset it back to baseline once you've clicked out of the box.

You can also opt to attach a click handler onto the modal itself, and write the logic accordingly. (one use case might be that this handler attaches or removes an event listener for a mouseover event on the modal and closes it once the mouse exits the modal)

Hope this helps!

  • Related