useClickOutside Custom Hook

May 12, 2023

React Hooks

useClickOutside Custom Hook

Thuta Sann

Thuta Sann

In this section, useClickOutside Custom Hook will be written.


Share This Snippet To :

UseOnClickOutside React Custom Hook

This useOnClickOutSide Hook is used for handling the outside of the RefObject.

Example Usages: Modals, PopUps, AutoComplete Search Results, etc.

import { RefObject, useEffect } from 'react' const useOnClickOutside = (ref: RefObject<HTMLDivElement | HTMLUListElement>, handler: Function) => { useEffect(() => { const listener = (event: any) => { // Do nothing if clicking ref's element or descendaent elements if (!ref.current || ref.current.contains(event.targe)) { return } handler() } document.addEventListener('mousedown', listener) document.addEventListener('touchstart', listener) return () => { document.removeEventListener('mousedown', listener) document.removeEventListener('touchstart', listener) } }, [ref, handler]) } export default useOnClickOutside // Usage const resultsContainer = useRef<HTMLDivElement>(null) useOnClickOutside(resultsContainer, () => setShowSearchResults(false))

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?