Home > Blockchain >  What is the most intelligent way to close the Dropdown Menu on clicking outside of its scope?
What is the most intelligent way to close the Dropdown Menu on clicking outside of its scope?

Time:04-04

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.

CodePudding user response:

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);
  • Related