skip to Main Content

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


  1. The issue you’re facing is related to how you’re comparing ref.current and e.target.

    const useOutsideClick = (ref, callback) => {
      const handleClick = (e) => {
        if (ref.current && !ref.current.contains(e.target)) {
          callback();
        }
      };
    
      useEffect(() => {
        document.addEventListener("click", handleClick);
    
        return () => {
          document.removeEventListener("click", handleClick);
        };
      }, [ref, callback]);
    };
    

    You should use the contains method or check if one element is an ancestor of the other.

    Login or Signup to reply.
  2. 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.

        const useOutsideClick = (ref, callback) => {
      const handleClick = (e) => {
        if (ref.current && !ref.current.contains(e.target)) {
          callback();
        }
      };
    
      useEffect(() => {
        document.addEventListener("click", handleClick);
    
        return () => {
          document.removeEventListener("click", handleClick);
        };
      }, [ref, callback]);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search