import React, { useEffect, useRef } from 'react'; import { usePopper } from 'react-popper'; import { useDropdownContext } from './context'; type DropdownPlacement = 'top' | 'top-start' | 'top-end' | 'right' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left'; export interface IDropdownContentProps { children: any; placement?: DropdownPlacement; className?: string; onOutsideClick?(e: any): void; [x: string]: any; } export const DropdownContent: React.FC = (props) => { const { className, children, onOutsideClick, placement = 'bottom', otherProps} = props; const { visible, toggleRef, setVisible } = useDropdownContext(); const refDropdownContent = useRef(null); const { styles, attributes } = usePopper(toggleRef?.current, refDropdownContent?.current, { placement: placement, modifiers: [ { name: 'offset', enabled: true, options: { offset: [0, 5], }, }, ], }); const handleClickOutside = (e: Event) => { if (refDropdownContent.current.contains(e.target)) { return; } else { setVisible(false); onOutsideClick && onOutsideClick(e); } }; const getClassNames = (visible: boolean, className: string) => { let classList = 'b-dropdown-content'; if (visible) classList += ` is-visible`; if (className) classList += ` ${className}`; return classList; }; useEffect(() => { if (visible) { document.addEventListener('click', handleClickOutside); } else { document.removeEventListener('click', handleClickOutside); } return () => { document.removeEventListener('click', handleClickOutside); }; }, [visible]); return (
{children}
); };