Material UI - backdrop triggers onClick on its children

Viewed 1516

I am using material UI backdrop and want to have some some tiny form inside of it. But whenever i click on its children the backdrop closes thanks to onClick which supposed to toggle the backdrop.

Is there any way how to stop backdrop onClick from triggering from inside backdrop (it's children) ?

I have tried to use useRef for elements inside but to me it seems crazy to have multiple referencies on elements and checking them in toggle function if it supposed to hide backdrop or not. Also i don't have access to some elements inside of the backdrop;

const handleBackdropToggle = e => {
  console.log(e.currentTarget === backdropRef.current);
  if (e.currentTarget === backdropRef.current) {
    setOpen(!open);
  }
};

const handleToggle = e => {
  setOpen(!open);
};
<Backdrop
  className={classes.backdrop}
  open={open}
  onClick={handleBackdropToggle}
  ref={backdropRef}
>
  <div className={classes.form}>
    <CommonFormCard
      noBorder={true}
      onSubmit={onSubmit}
      onBack={handleToggle}
      submitButtonText={`Odeslat`}
    >
      <>
        <h4>Od kdy má fotograf nafotit nemovitost?</h4>
        <CommonForm formData={renderFormData} onChange={onChange} />
      </>
    </CommonFormCard>
  </div>
</Backdrop>;
1 Answers

Rather than toggling your backdrop via onClick on the backdrop, you can use the Click away listener.

The main issue that you are likely experiencing is that you need to stop the propagation of click events in the form. The nature of DOM events is that they propagate up to all ancestors by default. You can prevent this with:

<div className={classes.form} onClick={e => e.stopPropagation()}>
Related