Skip to content

Commit

Permalink
Added outside click to toggle the dropdown
Browse files Browse the repository at this point in the history
  • Loading branch information
SansCaar committed Jul 18, 2024
1 parent 07244c4 commit 7772e69
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
28 changes: 26 additions & 2 deletions nepalingo-web/src/components/header/ChangeLanguage.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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<HTMLDivElement>(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);
Expand All @@ -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 (
<div className="relative text-left h-full">
<div ref={dropdownRef} className="relative text-left h-full">
<button
type="button"
className="w-full bg-grayDark px-6 h-10 rounded-lg text-sm font-medium text-gray-900 focus:outline-none"
Expand Down
3 changes: 1 addition & 2 deletions nepalingo-web/src/components/header/Menu.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from "react";
import { LanguageKey } from "../../hooks/Langauge";
import { LanguageKey } from "@hooks/Langauge";

interface MenuProps {
isOpen: boolean;
Expand All @@ -9,7 +9,6 @@ interface MenuProps {

const Menu: React.FC<MenuProps> = ({ isOpen, onSelect, options }) => {
if (!isOpen) return null;
console.log(options)

return (
<div className="origin-top-right absolute left-0 mt-2 rounded-lg shadow-lg bg-grayDark ring-1 ring-black ring-opacity-5 focus:outline-none overflow-hidden">
Expand Down

0 comments on commit 7772e69

Please sign in to comment.