-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathuseComponentVisibility.tsx
More file actions
32 lines (27 loc) · 1.03 KB
/
Copy pathuseComponentVisibility.tsx
File metadata and controls
32 lines (27 loc) · 1.03 KB
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
import React from 'react';
export const useComponentVisibility = (ref: React.RefObject<HTMLInputElement>) => {
const [is_dropdown_visible, setDropdownVisibility] = React.useState(false);
const handleHideDropdown = (event: KeyboardEvent) => {
if (event.key.toUpperCase() === 'ESCAPE') {
setDropdownVisibility(false);
}
};
const handleClickOutside = (event: Event) => {
if (!ref?.current?.contains(event.target as Node)) {
setDropdownVisibility(false);
}
};
React.useEffect(() => {
document.addEventListener('keydown', handleHideDropdown, true);
document.addEventListener('click', handleClickOutside, true);
return () => {
document.removeEventListener('keydown', handleHideDropdown, true);
document.removeEventListener('click', handleClickOutside, true);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return {
is_dropdown_visible,
setDropdownVisibility,
};
};