this is a clickedOutside hook:
const useOutsideClick = (ref: RefObject<HTMLElement>, callback: () => void) => {
const handleClick = (e: any) => {
console.log(ref.current, e.target);
if (ref.current && ref.current == e.target) {
// callback();
console.log("SUCCESS");
}
};
useEffect(() => {
document.addEventListener("click", handleClick);
return () => {
document.removeEventListener("click", handleClick);
};
});
};
Even though it logs the same elements in line 3, the condition i.e: (ref.current && ref.current == e.target)
is not fulfilled.
I tried it with contains
too. what is happening here?
2
Answers
The issue you’re facing is related to how you’re comparing
ref.current
ande.target
.You should use the
contains
method or check if one element is an ancestor of the other.Missing Dependency Array in useEffect: In the useEffect hook, you should provide a dependency array to specify when the event listener should be added and removed. Since you are using ref in the handleClick function, it should be included in the dependency array to ensure that the event listener is updated correctly when ref changes.