useToggleuseToggle+useEventRefuseSafeEffectuseEventControluseDebounceuseThrottleuseClickOutsideuseTabsuseDateuseDatesuseImageuseCaptureuseIntersectionObserver
react react-hook ironman30

useClickOutside

A Hook to trigger callback when user clicks on outside of the target


LINKS

鐵人賽連結


function useClickOutside(cb) {
  const ref = useRef()

  useEffect(() => {
    const handleClick = (event) => {
      const target = event.target

      const isInside = ref.current.contains(target)

      if (!isInside) {
        //do the job
        cb()
      }
    }

    document.addEventListener("click", handleClick)

    return () => {
      document.removeEventListener("click", handleClick)
    }
  }, [])

  return ref
}

Params

name type description
cbfunctioncallback function to fire on condition

Return

name type description
refObjectsuppose to attach on DOM element

Example