Translations for React using i18n hook

Translations for React using i18n hook

June 25, 2020

react

Recently in my work, the need to include translations to a project built with React arose. I had to investigate and came to this solution, which I think someone might find helpful.

Installation of necessary packages

For the installation of these packages, we will need to have previously installed and configured npm.

Once we have npm installed we must install the following packages:

npm install --save i18next
npm install --save react-i18next
npm install --save i18next-browser-languagedetector

Create a file where translations will be stored

We will create a folder called translations within src and, within the translations folder, we will create a folder for each language to which we want to add the translations.

./src
    ./translations
        ./es
            ./translations.js

We will create the translation.js file where the translations stored in this case for the Spanish language:

// File: translations.js
 
export const TRANSLATIONS_ES = {
    female: 'Femenino',
}

Create the configuration file for i18n

./src
    ./translations
        ./i18n.js

with the following content:

// File: i18n.js
 
import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
 
// import translations file
import { TRANSLATIONS_ES } from '../translations/es/translations'
 
i18n.use(LanguageDetector)
    .use(initReactI18next)
    .init({
        resources: {
            es: {
                // use translations file for spanish resources
                translation: TRANSLATIONS_ES,
            },
        },
    })

Using the hook for translations in component

// File: ExampleComponent.js
 
// import hook for translations and i18n configuration file
import { useTranslation } from "react-i18next";
import '../../translations/i18n.js';
 
export const ExampleComponent = () => {
 
	// destructuring t() function for useTranslation()
    const { t } = useTranslation();
 
    return (
        {// using t() function for translate}
        <p>{ t('female') }</p>
    )
}

Thanks for reading me. 😊