From bce1f8e2933fadb647c6f4f687b306bdbe24e9ae Mon Sep 17 00:00:00 2001 From: OGBONNA SUNDAY <62995161+SunGoldTech@users.noreply.github.com> Date: Tue, 6 Sep 2022 17:56:20 +0100 Subject: [PATCH] fix: Filter dropdown can only be closed by clicking on the filter button (#299) Fixes #292 --- .../superlative-selector.tsx | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/components/molecules/SuperlativeSelector/superlative-selector.tsx b/components/molecules/SuperlativeSelector/superlative-selector.tsx index ae0b4fff71..c8be4b098d 100644 --- a/components/molecules/SuperlativeSelector/superlative-selector.tsx +++ b/components/molecules/SuperlativeSelector/superlative-selector.tsx @@ -1,6 +1,6 @@ import ContextFilterButton from "components/atoms/ContextFilterButton/context-filter-button"; import ContextFilterOption from "components/atoms/ContextFilterOption/context-filter-option"; -import React, { useState } from "react"; +import React, { useEffect, useRef, useState } from "react"; import Icon from "../../atoms/Icon/icon"; import cancelIcon from "public/x-circle.svg"; import Radio from "components/atoms/Radio/radio"; @@ -17,13 +17,31 @@ const SuperativeSelector: React.FC = ({ handleCancelClick, selected }) => { + const ref = useRef(null); const [isOpen, setIsOpen] = useState(false); const toggleFilter = () => { setIsOpen(!isOpen); }; + useEffect(() => { + const checkIfClickedOutside = (e: any) => { + // If the menu is open and the clicked target is not within the menu, + // then close the menu + if (isOpen && ref.current && !ref.current.contains(e.target)) { + setIsOpen(false); + } + + }; + document.addEventListener("mousedown", checkIfClickedOutside); + + return () => { + // Cleanup the event listener + document.removeEventListener("mousedown", checkIfClickedOutside); + }; + }, [isOpen]); + return ( -
+
{selected ? (