Home > Enterprise >  Uncaught TypeError: Cannot read properties of undefined using React and useRef
Uncaught TypeError: Cannot read properties of undefined using React and useRef

Time:08-15

So this is the function that I handle outside the target click to close some models and stuff, but an error message on the console shows an error message like the following:

Uncaught TypeError: Cannot read properties of undefined (reading 'contains')

And I'm wondering how to handle the undefined so the function doesn't call, or at least hide from the console.

Here is how I handle it:

 let useClickOutside = (handler) => {
        let domNode = useRef();

        useEffect(() => {
            let maybeHandler = (event) => !domNode.current.contains(event.target) && handler();
            document.addEventListener("mousedown", maybeHandler);
            return () => document.removeEventListener("mousedown", maybeHandler);
        });

        return domNode;
    };

CodePudding user response:

Solution 1: Use Optional chaining (?.)

let useClickOutside = (handler) => {
        let domNode = useRef();

        useEffect(() => {
            let maybeHandler = (event) => !domNode.current?.contains(event.target) && handler();
            document.addEventListener("mousedown", maybeHandler);
            return () => document.removeEventListener("mousedown", maybeHandler);
        });

        return domNode;
    };

Solution 2: Use Logical AND (&&)

 let useClickOutside = (handler) => {
        let domNode = useRef();

        useEffect(() => {
            let maybeHandler = (event) =>  domNode.current && !domNode.current.contains(event.target) && handler();
            document.addEventListener("mousedown", maybeHandler);
            return () => document.removeEventListener("mousedown", maybeHandler);
        });

        return domNode;
    };
  • Related