-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathuseDropdown.ts
51 lines (48 loc) · 1.44 KB
/
useDropdown.ts
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Options } from '@popperjs/core';
import { useState } from 'react';
import { usePopper } from 'react-popper';
import { useClickAway } from 'react-use';
// TODO: better keyboard navigation
export default function useDropdown(config: Partial<Options>) {
const [isOpen, setIsOpen] = useState(false);
const [toggleElement, setToggleElement] = useState<HTMLElement | null>(null);
const [arrowElement, setArrowElement] = useState<HTMLElement | null>(null);
const [menuElement, setMenuElement] = useState<HTMLElement | null>(null);
useClickAway({ current: toggleElement }, () => isOpen && setIsOpen(false), [
'click',
]);
const popper = usePopper(toggleElement, menuElement, {
...config,
modifiers: [
{ name: 'arrow', options: { element: arrowElement } },
{
name: 'preventOverflow',
options: {
altAxis: true,
padding: 10,
},
},
...(config.modifiers || []),
],
});
const visibility: 'visible' | 'hidden' = isOpen ? 'visible' : 'hidden';
return {
isOpen,
setIsOpen,
toggleProps: {
ref: setToggleElement,
onClick: () => setIsOpen(!isOpen),
},
arrowProps: { ref: setArrowElement, style: popper.styles.arrow },
menuProps: {
role: 'menu',
ref: setMenuElement,
style: {
...popper.styles.popper,
visibility,
},
...popper.attributes.popper,
},
itemProps: { role: 'menuitem' },
};
}