Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Last active October 1, 2022 03:40
Show Gist options
  • Save Phryxia/2b3f884345261fbd19b95505ced8eabc to your computer and use it in GitHub Desktop.
Save Phryxia/2b3f884345261fbd19b95505ced8eabc to your computer and use it in GitHub Desktop.
Simple react hook implementation for detecting click of outside of the given DOM
import { useEffect, useRef } from 'react'
export function useOutsideClickHandler<T extends HTMLElement>(
callback: (e: MouseEvent) => void
) {
const ref = useRef<T>(null)
useEffect(() => {
function handleClick(e: MouseEvent): void {
if (!ref.current?.contains(e.target as Node)) {
callback(e)
}
}
document.addEventListener('click', handleClick)
return () => document.removeEventListener('click', handleClick)
}, [callback])
return ref
}
@Phryxia
Copy link
Author

Phryxia commented Apr 10, 2022

Example

function Component() {
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
  const modalRef = useOutsideClickHandler<HTMLDivElement>(() => setIsModalOpen(true))
  
  return (
    <div>
      <button onClick={() => setIsModalOpen(true)}>Open</button>
      {isModalOpen && <div ref={modalRef}>I'm Modal</div>}
    </div>
  )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment