score:1

Accepted answer

sounds like you just need to check if the ref exists first:

const onbodyclick = (event) => {
  if (!ref.current) {
    // component is unmounting
    // below line could be used or commented out; since the component is unmounting,
    // the state should not make a difference
    // setopen(false);
    return
  }
  if (ref.current.contains(event.target)) {
    // component is not unmounting, and click was inside ref
    return;
  }
  // component is not unmounting, and click was outside ref
  setopen(false);
};

score:0

i have the same problem and this is working for me


if(this.wrapperref && !this.wrapperref.contains(event.target) {
 this.setstate({visibility: false});
}

i check if wrapperref exists and i check if the wrapper contains the html element

i know you are using react hooks, but the idea is the same.


Related Query

More Query from same tag