How to translate your React.js app with i18next
Tags: react, beginners, tutorial
Published: 2019-05-03 16:00:20

---
title: How to translate your React.js app with i18next
published: true
description: Today I'll show you how to translate text and date in your React.js app.
tags: react,beginner,tutorial 
---
Today, I will show you how to translate the text and date in your React.js application.

First of all, you must install some dependencies:

```
yarn add i18next i18next-xhr-backend i18next-browser-languagedetector react-i18next
```


Now we need to create a file called __i18n.js__ in our _src_ folder: 
```javascript
import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';

const fallbackLng = ['en']; 
const availableLanguages = ['en', 'ru'];

i18n
  .use(Backend) // load translation using xhr -> see /public/locales. We will add locales in the next step
  
  .use(LanguageDetector) // detect user language
  
  .use(initReactI18next) // pass the i18n instance to react-i18next.
  
  .init({
    fallbackLng, // if user computer language is not on the list of available languages, than we will be using the fallback language specified earlier
    debug: true,
    whitelist: availableLanguages,

    interpolation: {
      escapeValue: false
    },
  });

export default i18n;
```
Then we will import i18n in __index.js__ in _src/index.js_:

```javascript
...
import './i18n';

ReactDOM.render(<App />, document.getElementById('root'));
...
```

The next step is to create our locales: _public/locales/en/translation.json_ and _public/locales/ru/translation.json_. This translation will be loaded automatically thanks to i18next-xhr-backend.

Also, in our _App.js_ we need to add Suspense in oder to display a loading indicator. 

```javascript
import React, { Suspense } from 'react';
...
function App() {
  return (
    <div className="App">
      <Suspense fallback={(<div>Loading</div>)}>
      <WeatherForecast /> 
      </Suspense>
    </div>
  );
}
...
```

Now we go to the component that we want to translate. If you have a Class Component we will be using the Higher Order Component __withTranslation__:

```javascript
import React, { Component } from 'react';
import { withTranslation } from 'react-i18next';

class News extends Component {

   render(){
     const { t } = this.props;
     
     return (
       <h1>{t('news.title')}</h1>
     )
   };
};

export default withTranslation()(News);

```
If you have a Functional Component you should use the react hook __useTranslation__:

```javascript
import React from 'react';
import { useTranslation } from 'react-i18next';

const WeatherForecast = () => {
  const { t } = useTranslation();
  return (
    <h1>{t('weather.title')}</h1>
  )
};

export default WeatherForecast;
```

Now we will modify our locales. In _public/locales/en/translation.json_:

```json
{
  "news": {
    "title": "Our news"
  },
  "weather": {
    "title": "Weather forecast"
  }
}
```
In _public/locales/ru/translation.json_:
```json
{
  "news": {
    "title": "Наши новости"
  },
  "weather": {
    "title": "Прогноз погоды"
  }
}
```
If you want to translate a phrase with a variable in it, you need do this:

```javascript
  <p>{t('weather.temprature', {number: temprature})}</p>
```
And in your .json locale file you need to write:
```json
  "temprature": "Today in Lyon is cloudy: {{number}}°C."
``` 
We will the same do for our Russian or any other version. 

Now I will show you how to translate a date. To do this I will be using moment.js. 

```
yarn add moment
```
In my __WeatherForecast.js__ I add: 

```javascript
<p>{t('weather.date', {date: Date.now()})}</p>
```

Now in _public/locales/en/translation.json_:

```json
"weather": {
        "date": "Today's date: {{date, currentDate}}"
    },
```

Here in `{{}}`  _date_ is __value__, variable that we asigned in our component and _currentDate_ is the __format__ that we will use next.

In our i18n.js file, we must import moment.js and configure the translation for our date: 

```javascript
import moment from 'moment';

...

availableLanguages.forEach((element) => {
  if (element !== 'en') {
     import(`moment/locale/${element}`);
   }
}); // we are importing only the locales that we need.

.init({
    ...
    interpolation: {
      escapeValue: false, 
       format: (value, format, lng) => {
        if (format === 'currentDate') return 
           moment(value).locale(lng).format('LL');
          return value;
       },//if the format is 'currentDate', then take its __value__ transfom it to a moment object, translate it to the current language and show it in Month DD, YYYY format.    
    },
  });
```

It should work well. Hope this article was helpful.