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?
Here is an codepen with the example
Your code works if you don't use event capturing.
document.addEventListener('click', handleClick);
return () => {
document.removeEventListener('click', handleClick);
};