Skip to Content
DocsRecipesSet up translations in a frontend module

Setting up translations in a frontend module

Internationalization is the process of designing software applications to be adapted easily for different languages and regions without requiring significant engineering changes. The goal of internationalization is to make the application locale-aware, meaning that it can be easily adapted to different locales or regions without requiring any changes to the codebase. We use react-i18next  to internationalize frontend module content.

In order to internationalize your frontend module, add this line in the src/index.ts file to tell the app shell where to find the translation files. This must be exported so the app shell can access it.

export const importTranslation = require.context("../translations", false, /.json$/, "lazy");

Keep the "lazy" mode. The app shell expects importTranslation to return a promise when it asks a module for a translation file.

All translations are added in the translations directory, which is at the top level of the package. The source file for translations is en.json, which contains English translations of all hardcoded text. To add translations for another language, for example Spanish, create a new es.json file in the translations directory. Use underscores for region-specific locale filenames, such as es_MX.json or pt_BR.json. The app shell converts detected language tags such as pt-BR to pt_BR before loading the JSON file. When the user changes their preferred language, the application loads the appropriate resource file and displays the text in the user’s preferred language.

Here is an example of using react-i18next localization in your React components.

import { useTranslation } from "react-i18next"; const ActiveVisitsTable = () => { const { t } = useTranslation(); return <h4>{t("activeVisits", "Active Visits")}</h4>; };

The framework provides a set of core translations that are used in many frontend modules. These can be used with the getCoreTranslation function. This function takes a core translation key, an optional default value, and optional i18next interpolation options. A TypeScript type error is shown if the provided key is not valid.

The valid core translation keys are defined by the CoreTranslationKey  type, which is generated from the coreTranslations map. These include common keys used in many apps, such as cancel, confirm, female, and other. The corresponding translation JSON files themselves live in the esm-translations  app.

import { getCoreTranslation } from "@openmrs/esm-framework"; const ErrorHeader = () => { return <h4>{getCoreTranslation("error", "Error")}</h4>; };
Last updated on