From 9e76f5842239a1e382110a0489630293324d96d7 Mon Sep 17 00:00:00 2001 From: Ujjwal Tyagi Date: Thu, 5 Sep 2024 18:43:51 +0530 Subject: [PATCH] Dropdown bug fixed (#353) Co-authored-by: Cody's Dad <40604284+AceTheCreator@users.noreply.github.com> --- components/Dropdown/dropdown.js | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/components/Dropdown/dropdown.js b/components/Dropdown/dropdown.js index 5ac4d485..1b2ae840 100644 --- a/components/Dropdown/dropdown.js +++ b/components/Dropdown/dropdown.js @@ -1,7 +1,20 @@ -import React, {useState} from 'react'; +import React, {useState,useRef,useEffect} from 'react'; function Dropdown({ active, items, setOptions, setOptions2 }) { const [show, setShow] = useState(false) + const dropdownRef = useRef(null); + useEffect(() => { + // This checks if the click event occurred outside the dropdown, if true we closes the dropdown. + function handleClickOutside(event) { + if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { + setShow(false); + } + } + document.addEventListener('mousedown', handleClickOutside); + return () => { + document.removeEventListener('mousedown', handleClickOutside); + }; + }, [dropdownRef]); return (
@@ -11,7 +24,7 @@ function Dropdown({ active, items, setOptions, setOptions2 }) { id='menu-button' aria-expanded='true' aria-haspopup='true' - onClick={() => setShow(true)} + onClick={() => setShow(!show)} >
{active}