-
-
Save washingtonsoares/b6d6330c6aa498809113c5632865132d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://letsbuildui.dev/articles/building-a-dropdown-menu-component-with-react-hooks | |
import { useState, useEffect, RefObject } from 'react'; | |
export const useDetectOutsideClick = (ref: RefObject<HTMLElement>, initialState: boolean) => { | |
const [isActive, setIsActive] = useState(initialState); | |
useEffect(() => { | |
const pageClickEvent = (event: MouseEvent) => { | |
// If the active element exists and is clicked outside of | |
if (ref.current !== null && !ref.current.contains(event.target as Node)) { | |
setIsActive(!isActive); | |
} | |
}; | |
// If the item is active (ie open) then listen for clicks | |
if (isActive) { | |
window.addEventListener('click', pageClickEvent); | |
} | |
return () => { | |
window.removeEventListener('click', pageClickEvent); | |
}; | |
}, [isActive, ref]); | |
return [isActive, setIsActive] as const; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment