Last active
February 7, 2019 19:42
-
-
Save artyomtrityak/72d539382faee18073d2011e7b4322a9 to your computer and use it in GitHub Desktop.
React Hooks custom hook use typescript
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
enum DROPDOWNS { | |
REPORT = "REPORT", | |
USER = "USER" | |
} | |
type IDropdowns = keyof typeof DROPDOWNS | null; | |
type IUseDropdown = [ | |
RefObject<HTMLInputElement>, | |
IDropdowns, | |
React.Dispatch<React.SetStateAction<IDropdowns>> | |
]; | |
const useDropdowns = (): IUseDropdown => { | |
const headerRef = useRef<HTMLInputElement>(null); | |
const openDropdownVarRef = useRef<IDropdowns>(null); | |
const [openDropdownName, setOpenDropdownName] = useState<IDropdowns>(null); | |
useEffect(() => { | |
function onGlobalClick(e: MouseEvent) { | |
if (!openDropdownName) { | |
return; | |
} | |
if (!(e.target instanceof Element)) { | |
return; | |
} | |
if (!headerRef.current || headerRef.current.contains(e.target)) { | |
return; | |
} | |
setOpenDropdownName(null); | |
} | |
window.addEventListener("click", onGlobalClick); | |
return () => { | |
return window.removeEventListener("click", onGlobalClick); | |
}; | |
}, [openDropdownName]); | |
return [ headerRef, openDropdownName, setOpenDropdownName ]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment