This repository has been archived on 2024-11-11. You can view files and clone it, but cannot push or open issues or pull requests.
react-component-form/example/components/Header/Language/index.tsx

81 lines
2.4 KiB
TypeScript
Raw Permalink Normal View History

import { useCallback, useEffect, useState, useRef } from "react"
import useTranslation from "next-translate/useTranslation"
import setLanguage from "next-translate/setLanguage"
import classNames from "clsx"
2022-08-26 20:19:31 +02:00
import i18n from "../../../i18n.json"
import { Arrow } from "./Arrow"
import { LanguageFlag } from "./LanguageFlag"
2022-08-26 20:19:31 +02:00
export const Language: React.FC = () => {
const { lang: currentLanguage } = useTranslation()
const [hiddenMenu, setHiddenMenu] = useState(true)
const languageClickRef = useRef<HTMLDivElement | null>(null)
const handleHiddenMenu = useCallback(() => {
2022-09-21 09:38:57 +02:00
setHiddenMenu((oldHiddenMenu) => {
return !oldHiddenMenu
})
2022-08-26 20:19:31 +02:00
}, [])
useEffect(() => {
const handleClickEvent = (event: MouseEvent): void => {
if (languageClickRef.current == null || event.target == null) {
return
}
if (!languageClickRef.current.contains(event.target as Node)) {
setHiddenMenu(true)
}
}
window.document.addEventListener("click", handleClickEvent)
2022-08-26 20:19:31 +02:00
return () => {
return window.removeEventListener("click", handleClickEvent)
2022-08-26 20:19:31 +02:00
}
}, [])
const handleLanguage = async (language: string): Promise<void> => {
await setLanguage(language)
}
return (
<div className="flex cursor-pointer flex-col items-center justify-center">
2022-08-26 20:19:31 +02:00
<div
ref={languageClickRef}
data-cy="language-click"
className="mr-5 flex items-center"
2022-08-26 20:19:31 +02:00
onClick={handleHiddenMenu}
>
<LanguageFlag language={currentLanguage} />
<Arrow />
</div>
<ul
data-cy="languages-list"
2022-08-26 20:19:31 +02:00
className={classNames(
"absolute top-14 z-10 mt-3 mr-4 flex w-24 list-none flex-col items-center justify-center rounded-lg bg-white p-0 shadow-lightFlag dark:bg-black dark:shadow-darkFlag",
{ hidden: hiddenMenu },
2022-08-26 20:19:31 +02:00
)}
>
{i18n.locales.map((language, index) => {
if (language === currentLanguage) {
return null
}
return (
<li
key={index}
className="flex h-12 w-full items-center justify-center pl-2 hover:bg-[#4f545c] hover:bg-opacity-20"
2022-09-21 09:38:57 +02:00
onClick={async () => {
await handleLanguage(language)
}}
2022-08-26 20:19:31 +02:00
>
<LanguageFlag language={language} />
</li>
)
})}
</ul>
</div>
)
}