Skip to content

Internationalization

Internationalization, or i18n (an abbreviation based on the number of letters between the initial "i" and the final "n"), is the process of designing and developing software, websites, or systems so they can be easily adapted to different languages, cultures, and regions without needing to be redeveloped.

Eitri provides a tool to facilitate the use of internationalization in your Eitri-Apps in just a few steps.

How to Use

The first step is to add the following property (if not already present) to eitri-app.conf.js: eitri-app-dependencies, with the internal property i18n in the following format. The options property is optional, but you can declare a fallback language as the default.

  "eitri-app-dependencies": {
    "i18n": {
      "options": {
        "fallbackLng": "pt"
      },
      "version": "14.1.2"
    }
  }

In the /src directory, you need to create a locales folder with the following structure:

src
└──  locales
    ├── en
    |   └── translation.json
    ├── pt
    |   └── translation.json
    ├── en_CA
    |    └── translation.json
    └── fr
        └── translation.json

Each translation.json file should contain the keys and values for the content to be translated. Example:

{
    "home": {
        "title": "Unlock Your Business Potential",
        "button": "Get Started Now ->"
    }
}

With this setup, you can dynamically fetch content in the desired language. Follow the example below:

import { useTranslation } from 'eitri-i18n'; // Import is required
import { Window, Text } from 'eitri-luminus';

export default function Home() {
    const { t } = useTranslation(); // Hook that returns the `t` method to fetch content dynamically based on the `locales` structure.

    return (
        <Window>
            <Text>
                {t("home.title")}
            </Text>
        </Window>
    );
}

If you want to change the language at the Eitri-App level, follow the example below:

import { useTranslation } from 'eitri-i18n'; // Import is required
import { Window, Text, Button } from 'eitri-luminus';
import { useState } from 'react';

export default function Home() {
    const [currentLanguage, setCurrentLanguage] = useState();
    const { t, i18n } = useTranslation(); // The `i18n` object has a `changeLanguage` method to change the language.

    const changeLanguage = () => {
        if (currentLanguage === "en-US") {
            i18n.changeLanguage("pt-BR");
            setCurrentLanguage("pt-BR");
        } else {
            i18n.changeLanguage("en-US");
            setCurrentLanguage("en-US");
        }
    };

    return (
        <Window>
            <Text>
                {t("home.title")}
            </Text>
            <Button
                marginTop="large"
                label="Switch Language"
                onPress={changeLanguage}
            />
        </Window>
    );
}