Having localized applications to 10+ languages, I understand that localizing your React application can be overwhelming. It feels like you have to make many code changes all over the application, which is true, but it can be easily done if we understand the i18next package. Without further delay, let’s dive in.
Installation:
We can install i18next using npm/yarn as follows
# npm
$ npm install i18next --save
# yarn
$ yarn add i18next
Initializing i18Next:
Create a file 18n.js under your ‘src’ folder
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import HttpApi from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(HttpApi) // Enables loading translation files over HTTP.
.use(LanguageDetector) // Detects user language.
.use(initReactI18next) // Initializes the react-i18next plugin.
.init({
supportedLngs: ['en', 'fr'], // Languages we're supporting.
fallbackLng: "en", // Fallback language if user's language isn't supported.
detection: {
order: ['cookie', 'htmlTag', 'localStorage', 'path', 'subdomain'], // Order of language detection.
caches: ['cookie'], // Cache the detected language in cookies.
},
backend: {
loadPath: '/assets/locales/{{lng}}/translation.json', // Path to the translation files.
},
});
export default i18n;
In the above code, we are specifying which plugins to use and configure different options. The above configuration is critical for switching between the languages.
Creating a translation file for each language:
Example:
// In en/translation.json
{
"welcomeText": "Welcome to the Website!"
}
// In es/translation.json
{
"welcomeText": "Bienvenido al sitio Web!"
}
// In fr/translation.json
{
"welcomeText": "Bienvenue sur le site."
}
Integrating i18next in Your Application
In your src/index.js
, import the i18n configuration:
import './i18n';
In our components, we can access translations by using useTranslation, which is a hook from react-i18next that gives access to the t function (for translation) and the i18n instance.
Example:
import React from 'react';
import { useTranslation } from 'react-i18next';
function App() {
const { t, i18n } = useTranslation();
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<div>
<h2>{t('welcomeText')}</h2>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('es')}>Espanol</button>
<button onClick={() => changeLanguage('fr')}>French</button>
</div>
);
}
export default App;
In the above example we are using t(‘welcomeText’) which fetches the translated text for the ‘welcomeText’ key based on the current language and changeLanguage is a function that changes the app’s current language when the corresponding button is clicked.
Conclusion:
This setup can be used to scale to more languages and features, making your application linguistically accessible.
Let me know if you have any questions, Let’s connect Rahul Haveri LinkedIn
Source link
lol