Last active
February 7, 2019 20:30
-
-
Save artyomtrityak/8fbf127fd69ebe7b2d415b3347af5a01 to your computer and use it in GitHub Desktop.
React hooks window addEventListener local variables
This file contains hidden or 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
import React, { useState, useRef, useEffect, RefObject } from "react"; | |
enum DROPDOWNS { | |
REPORT = "REPORT", | |
USER = "USER" | |
} | |
type IDropdowns = keyof typeof DROPDOWNS | null; | |
type IUseDropdown = [ | |
RefObject<HTMLInputElement>, | |
IDropdowns, | |
(val: IDropdowns) => void | |
]; | |
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 ]; | |
}; | |
function Header(props: IHeaderProps) { | |
const [ headerRef, openDropdownName, setOpenDropdownName ] = useDropdowns(); | |
return ( | |
<nav className="navbar navbar-expand-lg header" ref={headerRef}> | |
// ... | |
</nav> | |
); | |
} | |
export default Header; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment