feat(i18n): add i18n types, config, provider, context, and custom hook
This commit is contained in:
47
src/providers/LanguageProvider.tsx
Normal file
47
src/providers/LanguageProvider.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import type { Language } from '@/types/language';
|
||||
import { changeLanguage } from 'i18next';
|
||||
import { useLayoutEffect, type JSX, type PropsWithChildren } from 'react';
|
||||
import { initReactI18next, useTranslation } from 'react-i18next';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { LangaugeContext } from '@/contexts/LangaugeContext';
|
||||
import i18n from 'i18next';
|
||||
import i18nBackend from 'i18next-http-backend';
|
||||
|
||||
i18n
|
||||
.use(i18nBackend)
|
||||
.use(initReactI18next)
|
||||
.init({
|
||||
lng: 'en',
|
||||
interpolation: {
|
||||
escapeValue: false,
|
||||
},
|
||||
backend: {
|
||||
loadPath: `${window.location.origin}/i18n/{{lng}}.json`,
|
||||
},
|
||||
});
|
||||
|
||||
export const LanguageProvider = (props: PropsWithChildren): JSX.Element => {
|
||||
const [currentLanguage, setCurrentLangauge] = useLocalStorage<Language>(
|
||||
'language',
|
||||
'fa',
|
||||
);
|
||||
const { t } = useTranslation();
|
||||
|
||||
useLayoutEffect(() => {
|
||||
changeLanguage(currentLanguage);
|
||||
document.documentElement.dir = currentLanguage === 'fa' ? 'rtl' : 'ltr';
|
||||
document.documentElement.lang = currentLanguage;
|
||||
}, [currentLanguage]);
|
||||
|
||||
return (
|
||||
<LangaugeContext.Provider
|
||||
value={{
|
||||
language: currentLanguage,
|
||||
changeLanguage: setCurrentLangauge,
|
||||
t: t,
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</LangaugeContext.Provider>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user