0

In my reactjs app there are the component 'Modal'. It's an absolutely positionned block with x-index: 1000. One button in the component 'Menu' opens this modal in the main page. There is a function closing the modal box by clicking only outside the box. But modal closes by both outside and inside clicks - any conditions about clicking on the modal doesn't work and the box closes. Why doesn't work conditions like 'id' or 'z-index' of the modal box?

const clickOutModal= (event) => { 
     if(event.target.id !== 'mymodal') {    //condition when modal box mustn't close
     clickModalClose();                     // working function based on useState for closing the modal box
      }             
  };

document.body.addEventListener('click', clickOutModal);

The second variant of condition I tried was

if(event.target.zIndex !== '1000')
Irina
  • 41
  • 5

2 Answers2

0

you want to have a background div that covers the entire screen with a z-index of maybe 1, that has a click event to close the modal.

Then your modal sits over top of that div and has a z-index of something higher (1000).

Rick
  • 1,710
  • 8
  • 17
0

I think it would be good to separate the components. Have a modal and backdrop component.

Also, React has their own click events: onClick. You can read more about it here https://reactjs.org/docs/handling-events.html

So, within the Modal component, you can have something like this:

<React.Fragment>
   <Backdrop showModal={*T or F*} clicked={*Pass in function that handles click event*}/>
   <div>
      ...contents of modal
   </div>
</React.Fragment>

The Backdrop component represents the background. You can set the onClick event in that component and when it is clicked, it will fire the click event which you set on it.

sulaimanh
  • 21
  • 4