Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My hook to detect onClick, prevents onChange

I made a hook to detect inside and outside click for a component

const useDetectClick = (
  ref: RefObject<HTMLDivElement>,
  insideClick: () => void,
  outsideClick: () => void
) => {
  useEffect(() => {
    const handleClick = (event: MouseEvent) => {
      const { target } = event;
      if (ref.current && !ref.current.contains(target as Node)) {
        outsideClick();
      } else if (ref.current && ref.current.contains(target as Node)) {
        insideClick();
      }
    };

    document.addEventListener('click', handleClick, true);

    return () => {
      document.removeEventListener('click', handleClick, true);
    };
  }, [ref]);
};

Inside of the component it I have a group of checkboxes with labels. I want the callback I have on insideClick to run, but also the onChange when clicking on a checkbox.
Clicking the label works, I figure because of the label has default click functionality which means it gives focus to the element with the ID that is referenced. But clicking on the actual checkbox the event is prevented.

How can I get pass this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is an codepen with the example

>Solution :

Your code works if you don’t use event capturing.

document.addEventListener('click', handleClick);
return () => {
    document.removeEventListener('click', handleClick);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading