When using i18n for internationalization, we typically store translated text in one or more JSON files and access these texts through specific keys. If you want to dynamically fetch text using variables as keys, follow these steps:
1. Define Translation Files
First, ensure you have a translation file, such as translation.json, which contains translation keys and values for various languages. For example:
json{ "welcome_message": "Welcome", "farewell_message": "Goodbye" }
2. Initialize i18next
In your application, initialize i18next and load the translation files:
javascriptimport i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; i18n .use(initReactI18next) .init({ resources: { en: { translation: require('./locales/en/translation.json') } }, lng: "en", fallbackLng: "en", interpolation: { escapeValue: false } });
3. Use Variables as Keys
When you need to dynamically select which translated text to display based on certain conditions, use variables as keys to retrieve the corresponding text. Here's a simple example demonstrating how to implement this:
javascriptconst getMessage = (key) => { return i18n.t(key); }; const key = 'welcome_message'; console.log(getMessage(key)); // Output: Welcome
Practical Application Example
Suppose you are developing a multilingual website where users need to see a welcome message or a farewell message after logging in, depending on their actions. You can implement this as follows:
javascriptconst userAction = 'login'; // or 'logout' const key = userAction === 'login' ? 'welcome_message' : 'farewell_message'; const message = i18n.t(key); console.log(message); // If userAction is 'login', output: Welcome
This approach provides flexibility by enabling you to choose different translation keys based on various scenarios and conditions, making the application more dynamic and diverse.