DEV Community

Cover image for Translations for React using i18n hook
Jesús Mejías Leiva for Wealize

Posted on • Updated on • Originally published at blog.susomejias.dev

Translations for React using i18n hook

Introduction

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

Enter fullscreen mode Exit fullscreen mode

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"

}

Enter fullscreen mode Exit fullscreen mode

Create the configuration file for i18n

./src
    ./translations
        ./i18n.js

Enter fullscreen mode Exit fullscreen mode

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,
        },
    }
});
Enter fullscreen mode Exit fullscreen mode

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>
    )
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading me. 😊

thank you

Top comments (2)

Collapse
 
ushakovmaksym profile image
UMaks

Hi, thank you for your post. Is there any mechanism for choosing page language manually?

Collapse
 
susomejias profile image
Jesús Mejías Leiva

Yes, you must use the i18n changeLanguage() function, I attach a link to the official documentation, thank you very much for your comment 👍