Cannot read property 'contains' of null

Viewed 456

I have a react based app with a dropdown menu, this dropdown works as a navigation. What I have to achieve is that when I click outside the dropdown the dropdown should be closed. I tried using useEffect and useRef. Here is my code:

  useEffect( () => {
    const onClickOutsideNavbar = (event) => {
      if (ref.current.contains(event.target)) {
        return
      };

      setNavItemsOpen(false);
    };

    document.body.addEventListener("click", onClickOutsideNavbar)

    return () => {
      document.body.removeEventListener("click", onClickOutsideNavbar);
    }
  }, [])

My JSX has a li which renders each nav item and an ul as a parent also a button which is used to trigger the dropdown and a div which hold all of this.

Everything was working until I added react-router-dom to link my pages.

<div ref= {ref}>
  <button onClick={handleNavToggle}>Trigger</button>
  <ul>
    <Link to="/navitem"><li>Nav Item</li></Link>
    <Link to=""><li>Nav Item</li></Link>
    <Link to=""><li>Nav Item</li></Link>
  </ul>
</div>

Whenever I click on 2nd or 3rd link, nothing happens. But if I click on the first link which will take me to NavItem, then my react app crashes after showing the new component for 1 sec. The error is

Cannot read property 'contains' of null.

If anyone know the reason behind this error please explain it to me.

1 Answers

I think your ref might be undefined after change to new page. So contains method is null. I don't have enough information to conclude but you can use ? operator to prevent app crash.

if (ref?.current?.contains(event.target)) {
        return
      };
Related