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'
2
3import { useEventListener } from 'usehooks-ts'
4
5type Handler = (event: MouseEvent) => void
6
7function 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?.current
14
15 // Do nothing if clicking ref's element or descendent elements
16 if (!el || el.contains(event.target as Node)) {
17 return
18 }
19
20 handler(event)
21 })
22}
23
24export default useOnClickOutside

Usage

1import { useRef } from 'react'
2
3import { useOnClickOutside } from 'usehooks-ts'
4
5export default function Component() {
6 const ref = useRef(null)
7
8 const handleClickOutside = () => {
9 // Your custom logic here
10 console.log('clicked outside')
11 }
12
13 const handleClickInside = () => {
14 // Your custom logic here
15 console.log('clicked inside')
16 }
17
18 useOnClickOutside(ref, handleClickOutside)
19
20 return (
21 <button
22 ref={ref}
23 onClick={handleClickInside}
24 style={{ width: 200, height: 200, background: 'cyan' }}
25 />
26 )
27}

Edit on CodeSandbox

See a way to make this page better?
Edit there »