Skip to content

Commit

Permalink
fix: close dropdown when item is clicked
Browse files Browse the repository at this point in the history
- Modified Dropdown.Item to handle click events
- Added data attributes to Dropdown.Container for event handling
- Fixes #616

Co-Authored-By: Rami Abdou <[email protected]>
  • Loading branch information
devin-ai-integration[bot] and ramiAbdou committed Dec 12, 2024
1 parent f80fd35 commit cbea915
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions packages/ui/src/components/dropdown.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import React, { type PropsWithChildren, useContext, useRef } from 'react';
import React, {
type PropsWithChildren,
useContext,
useEffect,
useRef,
} from 'react';

import { useOnClickOutside } from '../hooks/use-on-click-outside';
import { cx } from '../utils/cx';

declare global {
interface Window {
[key: string]: any;
}
}

const DropdownContext = React.createContext({
_initialized: false,
});
Expand Down Expand Up @@ -49,23 +60,51 @@ Dropdown.Container = function DropdownContainer({
onClose,
}: DropdownContainerProps) {
const ref: React.MutableRefObject<HTMLDivElement | null> = useRef(null);
const closeFnId = useRef(
`dropdownClose${Math.random().toString(36).slice(2)}`
);

useEffect(() => {
window[closeFnId.current] = onClose as Window[string];

return () => {
delete window[closeFnId.current];
};
}, [onClose]);

useOnClickOutside(ref, onClose);

return (
<div className="relative" ref={ref}>
<div
className="relative"
ref={ref}
data-dropdown-container
data-onclose={closeFnId.current}
>
{children}
</div>
);
};

Dropdown.Item = function DropdownItem({ children }: PropsWithChildren) {
const handleClick = (e: React.MouseEvent<HTMLLIElement>) => {
const container = (e.target as HTMLElement).closest(
'[data-dropdown-container]'
);
const onClose = container?.getAttribute('data-onclose');

if (onClose && typeof window[onClose] === 'function') {
(window[onClose] as () => void)();
}
};

return (
<li
className={cx(
'border-b border-b-gray-200 last:border-b-0',
'dropdown-item'
)}
onClick={handleClick}
>
{children}
</li>
Expand Down

0 comments on commit cbea915

Please sign in to comment.