설치
yarn add i18next
yarn add i18next-browser-languagedetector
yarn add react-i18next
yarn add @types/react-i18next
i18n.ts
import i18next from 'i18next'
import detector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next'
import tranEn from './locales/en.json';
import tranKo from './locales/ko.json';
const resources = {
en: { translation: tranEn },
ko: { translation: tranKo },
}
i18next
.use(initReactI18next)
.use(detector)
.init({
detection:{order:['path','navigator']}, // default locale 우선순위 ( path -> browser detected)
resources,
fallbackLng: 'en',
keySeparator: false,
interpolation: {
escapeValue: false
}
})
export default i18next;
index.tsx
import './i18n'
components
import { useTranslation } from "react-i18next";
const component : FC = (props) =>{
const{t, i18n } = useTranslation();
const handleChangeLanguage = (lang:string) => {
i18n.changeLanguage(lang);
}
const locale = i18n.language.substring(0,2); /* browser detected 일 경우 'en-US', 'ko-KR' 형태이기 때문에 앞에 2자리만 사용 */
return(
<>
<Select defaultValue={locale} style={{width:100}} onChange={handleChangeLanguage}>
<Option value="en">{t('language_en')}</Option>
<Option value="ko">{t('language_ko')}</Option>
</Select>
</>
)
}