Skip to content

Instantly share code, notes, and snippets.

@artyomtrityak
Last active February 7, 2019 19:42
Show Gist options
  • Save artyomtrityak/72d539382faee18073d2011e7b4322a9 to your computer and use it in GitHub Desktop.
Save artyomtrityak/72d539382faee18073d2011e7b4322a9 to your computer and use it in GitHub Desktop.
React Hooks custom hook use typescript
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