From e16e26977570e61efa6f3340ad040c143e8e1cea Mon Sep 17 00:00:00 2001 From: Siddhant Rai Date: Fri, 21 Jun 2024 23:35:03 +0530 Subject: [PATCH] fix: dropdown closes on clicking outside --- frontend/src/components/Dropdown.tsx | 18 ++++++++++++++++++ frontend/src/components/SourceDropdown.tsx | 20 ++++++++++++++++++-- frontend/src/conversation/Conversation.tsx | 2 +- 3 files changed, 37 insertions(+), 3 deletions(-) diff --git a/frontend/src/components/Dropdown.tsx b/frontend/src/components/Dropdown.tsx index 89fe3df..17516aa 100644 --- a/frontend/src/components/Dropdown.tsx +++ b/frontend/src/components/Dropdown.tsx @@ -42,9 +42,26 @@ function Dropdown({ onDelete?: (value: string) => void; placeholder?: string; }) { + const dropdownRef = React.useRef(null); const [isOpen, setIsOpen] = React.useState(false); const borderRadius = rounded === 'xl' ? 'rounded-xl' : 'rounded-3xl'; const borderTopRadius = rounded === 'xl' ? 'rounded-t-xl' : 'rounded-t-3xl'; + + const handleClickOutside = (event: MouseEvent) => { + if ( + dropdownRef.current && + !dropdownRef.current.contains(event.target as Node) + ) { + setIsOpen(false); + } + }; + + React.useEffect(() => { + document.addEventListener('mousedown', handleClickOutside); + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, []); return (