-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathuseDropdown.ts
More file actions
35 lines (28 loc) 路 866 Bytes
/
Copy pathuseDropdown.ts
File metadata and controls
35 lines (28 loc) 路 866 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import React, { useRef, useState } from "react"
type useDropdownType = () => [
React.RefObject<HTMLDivElement>,
boolean,
() => void
]
function assertIsNode(e: EventTarget | null): asserts e is Node {
if (!e || !("nodeType" in e)) {
throw new Error(`Node expected`)
}
}
const useDropdown: useDropdownType = () => {
const menuRef = useRef<HTMLDivElement>(null)
const [isDropdownOpened, setIsDropdownOpened] = useState(false)
const handleClick: (this: Window, e: MouseEvent) => void = (e) => {
if (!menuRef.current) return
assertIsNode(e.target)
if (menuRef.current.contains(e.target) === false) {
setIsDropdownOpened(false)
}
}
const onOpenBtn = () => {
setIsDropdownOpened(true)
window.addEventListener("click", handleClick)
}
return [menuRef, isDropdownOpened, onOpenBtn]
}
export default useDropdown