To support multi-language, we can use i18next and react-18next libraries.
Basic Setup
internationalization.ts
import i18n from 'i18next';
import Backend from 'i18next-http-backend';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
// i18next-http-backend
// loads translations from your server
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next) // passes i18n down to react-i18next
.init({
fallbackLng: 'en',
detection: {
lookupLocalStorage: 'iws_lang',
},
interpolation: {
escapeValue: false, // react already safes from xss => https://www.i18next.com/translation-function/interpolation#unescape
},
debug: false,
});
export default i18n;
How To Use
We can simply import internationalization in the App.tsx, and locate translation.json file in the /public/locales/{language_code}, where country_code is iso short (6391) country code such as en, ko, etc.
And then, in the component, we can import useTranslation hooks.
import { useTranslation } from 'react--i18next';
in the functional component,
const { t } = useTranslation();
return <div>{t('greeting.hello')}</div>
Please make sure that the translation.json should have the defined string in the following structure.
{
"greeting": {
"hello": "good morning! hello hi!"
}
}
You can also use variables in the translation.json.
{
"greeting": {
"hello": "hi, {{name}}!"
}
}
And then, in the component,
<div>{t('greeting.hello', { name: 'Jim' })}</div>
and this results
hi, Jim!
Change Language Preference
You can change the language dynamically in the App.
import { useTranslation } from 'react-i18next';
and in the component
const { i18n } = useTranslation();
and then, put the language code that you want to switch to.
ex) i18n.changeLanguage('ko');
Top comments (0)