From 4d41f0b3b4e9a9178c457327c33f89f524174f3d Mon Sep 17 00:00:00 2001 From: siegfriedbz Date: Sun, 4 Aug 2024 11:44:33 +0800 Subject: [PATCH] Enable the PairSelector menu to close when clicking outside the menu --- src/app/components/PairSelector.tsx | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/app/components/PairSelector.tsx b/src/app/components/PairSelector.tsx index ab5f3382..7e2381bb 100644 --- a/src/app/components/PairSelector.tsx +++ b/src/app/components/PairSelector.tsx @@ -47,6 +47,8 @@ export function PairSelector() { const pairSelector = useAppSelector((state) => state.pairSelector); const dispatch = useAppDispatch(); + const menuRef = useRef(null); + const inputRef = useRef(null); const [query, setQuery] = useState(""); const [isOpen, setIsOpen] = useState(false); @@ -187,8 +189,26 @@ export function PairSelector() { } }, [isOpen, options, setFilteredOptions, setHighlightedIndex]); + const handleClickOutside = (event: MouseEvent) => { + if (menuRef.current && !menuRef.current.contains(event.target as Node)) { + setIsOpen(false); + } + }; + + useEffect(() => { + if (isOpen) { + document.addEventListener("click", handleClickOutside); + } else { + document.removeEventListener("click", handleClickOutside); + } + return () => { + document.removeEventListener("click", handleClickOutside); + }; + }, [isOpen]); + return (