Localization & Internationalization in React JS | Forget react-i18next

Santosh Yadav
2 min readNov 27, 2020

--

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.

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.

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 fall-back to English.

This is a re-post of my original post on blogspot — https://santosh-yadaav.blogspot.com/2020/09/localization-internationalization-in.html

--

--

Santosh Yadav
Santosh Yadav

No responses yet