Docs
Recipes
Set 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 (opens in a new tab) to internationalize frontend module content.

In order to internationalize your frontend module, add this line in the index.ts file to tell the app shell where to find the translation files.

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

All translations are added in the translations directory which is at the top level of the package. The source file for translations is the en.json which contains english translations of all hardcoded text. To add translations of another language eg. Spanish, create a new es.json file in the translations directory. 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 (opens in a new tab) function. This function takes two arguments: the first is the key of the core translation, and the second is the default value to return if the requested translation is not found. A Typescript type error is shown if the provided key is not valid.

The valid core translations are defined in the CoreTranslationKey (opens in a new tab) type. These include common strings used in many apps, such as Cancel, Confirm, Female, and Other. The corresponding translation JSON files themselves live in the esm-translations (opens in a new tab) app.

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