diff --git a/nepalingo-web/src/components/header/ChangeLanguage.tsx b/nepalingo-web/src/components/header/ChangeLanguage.tsx index 02d11c2..b11c2e6 100644 --- a/nepalingo-web/src/components/header/ChangeLanguage.tsx +++ b/nepalingo-web/src/components/header/ChangeLanguage.tsx @@ -1,4 +1,4 @@ -import React, { useState } from "react"; +import React, { useEffect, useRef, useState } from "react"; import Menu from "./Menu"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faChevronDown } from "@fortawesome/free-solid-svg-icons"; @@ -7,7 +7,31 @@ import { LanguageKey, Languages, useLanguage } from "../../hooks/Langauge"; const ChangeLanguage: React.FC = () => { const [isOpen, setIsOpen] = useState(false); const { selectedLanguage, switchLanguage } = useLanguage(); + const dropdownRef = useRef(null); + useEffect(() => { + const handleEscape = (event: KeyboardEvent) => { + if (event.key === "Escape") { + setIsOpen(false); + } + }; + const handleOutsideClick = (event: MouseEvent) => { + if (!dropdownRef.current?.contains(event.target as Node)) { + setIsOpen(false); + } + } + if (isOpen) { + document.addEventListener("click", handleOutsideClick); + } else { + document.removeEventListener("click", handleOutsideClick); + } + window.addEventListener("keydown", handleEscape); + + return () => { + window.removeEventListener("keydown", handleEscape); + document.removeEventListener("click", handleOutsideClick); + }; + }, [open]); const toggleMenu = () => { setIsOpen(!isOpen); @@ -20,7 +44,7 @@ const ChangeLanguage: React.FC = () => { const options = Object.keys(Languages).map((key) => ({ label: key, value: Languages[key as LanguageKey] })) console.log(options) return ( -
+