Skip to content

Instantly share code, notes, and snippets.

@zheeeng
Created March 30, 2021 10:15
Show Gist options
  • Select an option

  • Save zheeeng/50af56c43b15ea846df47a105e001530 to your computer and use it in GitHub Desktop.

Select an option

Save zheeeng/50af56c43b15ea846df47a105e001530 to your computer and use it in GitHub Desktop.

Revisions

  1. zheeeng created this gist Mar 30, 2021.
    29 changes: 29 additions & 0 deletions useClickOutside.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    import { useEffect, useRef } from 'react'

    export const useClickOutside = <T extends HTMLElement>(callback: (event: MouseEvent) => void) => {
    const ref = useRef<T>(null)

    const eventRef = useRef(callback)

    useEffect(
    () => {
    eventRef.current = callback
    },
    [callback]
    )

    useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
    if (event.target && ref.current && !ref.current.contains(event.target as Node)) {
    eventRef.current(event)
    }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
    document.removeEventListener('mousedown', handleClickOutside);
    };
    }, []);

    return ref
    }