Home > Mobile >  Close custom dropdown on clicking anywhere in the body in nextjs
Close custom dropdown on clicking anywhere in the body in nextjs

Time:12-13

I have created a custom dropdown with divs and spans. I handle opening and closing states with useState() hook. Now I want to close to dropdown whenever I click anywhere on the site just like the default <select> input. I can't use vanilla dom manipulation for example adding an event listener on document.querySelector(".element").

So how can I do it?

CodePudding user response:

you can create a custom hook

function useOnClickOutside(ref, handler) {
  useEffect(
    () => {
      const listener = (event) => {
        // Do nothing if clicking ref's element or descendent elements
        if (!ref.current || ref.current.contains(event.target)) {
          return;
        }
        handler(event);
      };
      document.addEventListener("mousedown", listener);
      document.addEventListener("touchstart", listener);
      return () => {
        document.removeEventListener("mousedown", listener);
        document.removeEventListener("touchstart", listener);
      };
    },
    // Add ref and handler to effect dependencies
    // It's worth noting that because passed in handler is a new ...
    // ... function on every render that will cause this effect ...
    // ... callback/cleanup to run every render. It's not a big deal ...
    // ... but to optimize you can wrap handler in useCallback before ...
    // ... passing it into this hook.
    [ref, handler]
  );
}

check here for more info https://usehooks.com/useOnClickOutside/

  • Related