Update context menu component

This commit is contained in:
Hazem Krimi
2021-04-22 01:53:21 +01:00
parent d9e2eb72c0
commit d1159e40df
2 changed files with 90 additions and 4 deletions
+66 -2
View File
@@ -1,7 +1,71 @@
import { useEffect, useRef, useState } from 'react';
import { Wrapper } from './styles';
import { Text } from '..';
const ContextMenu = () => {
return <Wrapper></Wrapper>;
type ContextMenuProps = {
className?: string;
items: Array<{ label: string; action: () => void }>;
component: string;
};
const ContextMenu = ({ items, component, className }: ContextMenuProps) => {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const openMenu = () => setOpen(true);
const handleClickOutside = (event: MouseEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
setOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
(document.querySelector(`#${component}`) as HTMLElement)?.addEventListener(
'mouseenter',
openMenu
);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
(document.querySelector(
`#${component}`
) as HTMLElement)?.removeEventListener('mouseenter', openMenu);
};
// eslint-disable-next-line
}, [ref]);
return (
<Wrapper
ref={ref}
className={className}
top={
(document.querySelector(`#${component}`) as HTMLElement)?.offsetTop + 30
}
left={
(document.querySelector(`#${component}`) as HTMLElement)?.offsetLeft +
10
}
>
{open && (
<ul>
{items.map(({ label, action }) => (
// eslint-disable-next-line
<li
onClick={() => {
setOpen(false);
action();
}}
key={label}
>
<Text variant='caption'>{label}</Text>
</li>
))}
</ul>
)}
</Wrapper>
);
};
export default ContextMenu;