Path: blob/master/cloud/ai-service-apps/nextjs-carbon-react-ui/src/hooks/useOutsideClick.js
6408 views
import { useRef, useEffect } from "react";12const useOutsideClick = (callback, exceptionDomIds) => {3const ref = useRef();45const isOutsideOfException = (target) => {6if (exceptionDomIds && exceptionDomIds.length > 0) {7return !exceptionDomIds.some((id) => {8const element = document.getElementById(id);9return element && element.contains(target);10});11}1213return true;14};1516const isOutsideOfElement = (target) => ref.current && !ref.current.contains(target);1718const handleClick = ({ target }) => {19if (isOutsideOfElement(target) && isOutsideOfException(target)) {20callback();21}22};2324useEffect(() => {25if (window !== undefined) {26document.addEventListener("click", handleClick);27}28return () => {29if (window !== undefined) {30document.removeEventListener("click", handleClick);31}32};33// eslint-disable-next-line react-hooks/exhaustive-deps34}, []);3536return ref;37};3839export { useOutsideClick };404142