2

I have created this simple Dropdown in React and everything works fine until I click outside the scope of the Dropdown. https://codesandbox.io/s/restless-fast-x2jhe8

I've added a min-height: 100vh property on the body, to replicate a full size page. Like I said, the functionality to close the Dropdown menu when we click anywhere in the page that is not the Dropdown, is not implemented yet. I am not sure how to handle this in the most elegant way. I tried something along the lines of adding an event listener on the body with useEffect and then checking if event.target has class dropdown, but it didn't perform as expected.

  • See: [Detect click outside React component](https://stackoverflow.com/questions/32553158/detect-click-outside-react-component) – Yogi Apr 03 '22 at 15:04

1 Answers1

1

I make this common hook in which I pass ref of that element and state which show or close modal

import { useEffect } from 'react';

function useOutsideClickManager(ref: React.RefObject<HTMLInputElement>, setIsOpen: React.Dispatch<React.SetStateAction<boolean>>) {
  useEffect(() => {
    function handleClickOutside(event: { target: EventTarget | Node | null }) {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [ref, setIsOpen]);
}
export { useOutsideClickManager };
  const [isOpen, setIsOpen] = React.useState(false);
  const wrapperRef = useRef<HTMLInputElement>(null);
  useOutsideClickManager(wrapperRef, setIsOpen);
Abbas Hussain
  • 1,277
  • 6
  • 14