forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLanguageSwitcher.js
More file actions
44 lines (38 loc) · 1.32 KB
/
Copy pathLanguageSwitcher.js
File metadata and controls
44 lines (38 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { useTranslation } from 'next-i18next';
import { useRouter, usePathname } from 'next/navigation';
import { useEffect, useState } from 'react';
const languages = [
{ code: 'en', name: 'English', dir: 'ltr' },
{ code: 'es', name: 'Español', dir: 'ltr' },
{ code: 'ar', name: 'العربية', dir: 'rtl' }
];
export default function LanguageSwitcher() {
const { i18n } = useTranslation('common');
const router = useRouter();
const pathname = usePathname();
const [currentLocale, setCurrentLocale] = useState(i18n.language || 'en');
useEffect(() => {
setCurrentLocale(i18n.language || 'en');
}, [i18n.language]);
const handleChange = (locale) => {
const newPath = pathname.replace(`/${currentLocale}`, `/${locale}`) || `/${locale}${pathname}`;
i18n.changeLanguage(locale);
router.push(newPath);
localStorage.setItem('preferredLocale', locale);
document.documentElement.dir = languages.find(l => l.code === locale)?.dir || 'ltr';
};
return (
<select
value={currentLocale}
onChange={(e) => handleChange(e.target.value)}
className="language-select"
style={{ padding: '0.4rem', borderRadius: '4px' }}
>
{languages.map((lang) => (
<option key={lang.code} value={lang.code}>
{lang.name}
</option>
))}
</select>
);
}