useOnClickOutside()
React hook for listening for clicks outside of a specified element (see useRef
).
This can be useful for closing a modal, a dropdown menu etc.
The Hook
1import { RefObject } from 'react'23import { useEventListener } from 'usehooks-ts'45type Handler = (event: MouseEvent) => void67function useOnClickOutside<T extends HTMLElement = HTMLElement>(8 ref: RefObject<T>,9 handler: Handler,10 mouseEvent: 'mousedown' | 'mouseup' = 'mousedown',11): void {12 useEventListener(mouseEvent, event => {13 const el = ref?.current1415 // Do nothing if clicking ref's element or descendent elements16 if (!el || el.contains(event.target as Node)) {17 return18 }1920 handler(event)21 })22}2324export default useOnClickOutside
Usage
1import { useRef } from 'react'23import { useOnClickOutside } from 'usehooks-ts'45export default function Component() {6 const ref = useRef(null)78 const handleClickOutside = () => {9 // Your custom logic here10 console.log('clicked outside')11 }1213 const handleClickInside = () => {14 // Your custom logic here15 console.log('clicked inside')16 }1718 useOnClickOutside(ref, handleClickOutside)1920 return (21 <button22 ref={ref}23 onClick={handleClickInside}24 style={{ width: 200, height: 200, background: 'cyan' }}25 />26 )27}
See a way to make this page better?
Edit there »