Ever Wondered How To Develop International Websites With Multiple Languages?
Tags: react, reactnative, javascript, webdev
Published: 2022-03-01 18:11:24

I've never cared about creating sites/apps in any other language asides English. The problem is, not everyone knows English, and a few weeks ago, my company required my team and I to develop an app for them with multi-language support. **How can you implement this feature?**

> *If you find this article interesting/useful, you owe me a like.*

---

###Disclaimer
I'm about to teach you how to implement translation in React/React Native, but don't worry if you use other library/framework. I'm sure there's an alternative and it would work similar with the solution I'm about to tell you.

###The Naive Approach
If you're an original thinker, here's how you'd do it. You might store a global variable, whether using **Redux** or **Context API** for each language you're supporting. That variable will be changed whenever the user changes the language. Also, the app will be dependent on that variable, and you might write explicit `if-else` or `switch-case` statements to render right content depending on the language. If you're slightly more advanced, you'd create separate `JSON` files for each language which would have key-value pairs of content and access them accordingly.

###The Ideal Approach
The previous method involves too much manual tasks. What if there's a library that could handle all these long, repetitive steps and abstract all the complexities?

There's a `NPM` package called `react-i18next` which solves this problem (it's also capable of more powerful stuffs too). 

* **Step 1: install dependencies**
```javascript
npm install react-i18next i18next --save
```

* **Step 2: add translation files**

Let's assume we're gonna support English and Arabic. Go ahead and add new files in these directories.

`src/translations/english/common.json`
```javascript
{
    "message": {
        "greeting": "Welcome."
    }
}
```

`src/translations/arabic/common.json`
```javascript
{
    "message": {
        "greeting": "أهلا بك"
    }
}
```

* **Step 3: edit** `index.js`
```javascript
import ReactDOM from 'react-dom';
import {I18nextProvider} from "react-i18next";
import i18next from "i18next";

import App from './App';
import englishContent from "./translations/english/common.json";
import arabicContent from "./translations/arabic/common.json";

i18next.init({
    interpolation: { escapeValue: false }, 
    lng: 'en',                              
    resources: {
        en: {
            common: englishContent             
        },
        ar: {
            common: arabicContent
        },
    },
});

ReactDOM.render(
    <React.StrictMode>
        <I18nextProvider i18n={i18next}>
            <App/>
        </I18nextProvider>
    </React.StrictMode>,
    document.getElementById('root')
);
```

* **Step 4: translate!**

Use the `t` function and supply key from your JSON file as shown below. You can access this function from any file.

```javascript
import {useTranslation} from "react-i18next";

function Component() {
    const {t, i18n} = useTranslation('common'); 
    // "common" because that's the name of files we created.
    // There are variations to this,
    // but I don't want to confuse you (you can
    // check the docs for more info)

    return <h1>{t('message.greeting)}</h1>;
}

export default Component;
```

###But How Do You Change Language?
If you paid attention to the code, in `index.js`, we used `en` and `ar` keys to represent English and Arabic. So, now we just need to change these keys to that of desired language using built-in function from `i18next` when the user switches the language (by clicking a button or something) and the changes will be reflected immediately.

```javascript
function Component() {
    const [t, i18n] = useTranslation('common');
    return <div>
        <h1>{t('message.greeting', {framework:'React'})}</h1>
        <button onClick={() => i18n.changeLanguage('en')}>English</button>
        <button onClick={() => i18n.changeLanguage('ar')}>عربي</button>
    </div>
}
```

> You can learn more from the official docs [here](https://react.i18next.com/).

If you find this article useful, you owe me a like. 😜