deepsite-pro / src /components /language-switcher /language-switcher.tsx
rexcorp1
Push Commit
acde83f
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { MdLanguage } from 'react-icons/md';
import classNames from 'classnames';
function LanguageSwitcher() {
const { t, i18n } = useTranslation();
const [isOpen, setIsOpen] = useState(false);
const [isIndonesian, setIsIndonesian] = useState(i18n.language.startsWith('id'));
const currentLanguage = isIndonesian ? 'id' : 'en';
// Switch language
const changeLanguage = (lng: string) => {
i18n.changeLanguage(lng);
setIsIndonesian(lng === 'id');
setIsOpen(false);
console.log('Language changed to:', lng);
// Set the page title to reflect the language change
document.title = t('app.title');
};
// Check if it's the first visit, only add the blinking effect on the first visit
const [highlight, setHighlight] = useState(false);
useEffect(() => {
// Check local storage to determine if it's the first visit
const hasVisitedBefore = localStorage.getItem('hasVisitedBefore');
// If it's the first visit, add the blinking effect and record it in local storage
if (!hasVisitedBefore) {
const timer = setInterval(() => {
setHighlight(prev => !prev);
}, 1000);
// Stop blinking after 5 seconds
setTimeout(() => {
clearInterval(timer);
setHighlight(false);
// Record that the user has visited
localStorage.setItem('hasVisitedBefore', 'true');
}, 5000);
return () => {
clearInterval(timer);
};
}
}, []);
return (
<div className="relative">
<button
className={classNames(
"relative overflow-hidden cursor-pointer flex-none flex items-center justify-center rounded-md text-xs lg:text-sm font-semibold py-1.5 px-3 text-white shadow-sm dark:shadow-highlight/20 mx-2 transition-all duration-300",
{
"bg-blue-600 hover:bg-blue-500": !highlight,
"bg-pink-500 hover:bg-pink-400": highlight,
}
)}
onClick={() => setIsOpen(!isOpen)}
>
<MdLanguage className="mr-1 text-lg" />
{isIndonesian ? 'ID' : 'EN'}
</button>
<div
className={classNames(
"absolute top-full mt-2 right-0 z-30 bg-white border border-gray-200 rounded-lg shadow-lg transition-all duration-75 overflow-hidden",
{
"opacity-0 pointer-events-none": !isOpen,
"opacity-100": isOpen,
}
)}
>
<ul className="py-1 text-sm text-gray-700">
<li>
<button
className={classNames(
"w-full px-4 py-2 text-left hover:bg-gray-100",
{
"font-bold bg-blue-50": currentLanguage === 'en',
}
)}
onClick={() => changeLanguage('en')}
>
{t('language.en')}
</button>
</li>
<li>
<button
className={classNames(
"w-full px-4 py-2 text-left hover:bg-gray-100",
{
"font-bold bg-blue-50": currentLanguage === 'id',
}
)}
onClick={() => changeLanguage('id')}
>
{t('language.id')}
</button>
</li>
</ul>
</div>
{/* Click outside to close the dropdown */}
{isOpen && (
<div
className="fixed inset-0 z-20"
onClick={() => setIsOpen(false)}
/>
)}
</div>
);
}
export default LanguageSwitcher;