Localization & Internationalization in React JS | Forget react-i18next

We are going to build a react web app which will have localization feature, but we are not going to use react-i18next. If you are building something smaller and scalable then we can use simple JS coding techniques to achieve that. We do not require (heavy - as compare to your project size) react-i18next package. It will be simple and accurate to provide localization for your app. I have made youtube video on this topic as well, you can watch (in English or in Hindi) video on the topic.

So, lets get on writing some code.

#1 Create a folder named translations and inside that create number of folders (number of locales, you wish to support), such en, fr, hi, de etc.

#2 Create index.js in each folder. Assign key-value pair to an object. The key should be unique and that have to use in other locale folder.

e.g. 

const en = {
  'overview' : 'Overview',
  'create' : 'Create'
};
export default en;

#3 Now we need to work on core logic. Create a index.js in translations folder and import all locale file(s) which you just created. 

import de from './de';
import en from './en';
const translations = {
  de,
  en
};
const getTrans = (
  key,
  locale = 'en'
=> {
  const currTranslation = translations[locale] ? translations[locale] : en;
  let transWord = currTranslation[key]
    ? currTranslation[key]
    : en[key]
    ? en[key]
    : key;

  return transWord;
};

export { getTrans };

Here, we are passing a key and trying to check on the locale file. If it is present then we will retrieve it else we have fallback to English.

Here is the Youtube Video:

Comments

Popular Posts