How to manage translations within React components

Introduction

Until now, translation management withing React components has often relied on hardcoded solutions. However, as the need for internationalization grows, it’s crucial to adopt more flexible and scalable approaches. Whether we’re building with React or Angular, incorporating translation capabilities is essential for the project’s future. At the moment, we’re leveraging the existing Angular service to integrate and handle translations in React too.

Step-by-Step Guide

  1. Create keys in messages_en.json:

    1. Open your messages_en.json file.

    2. Add the translation keys along with their respective messages:

      { "translationKey": "Translation Key", "translationKey.withParams": "Translation Key ${id}" }
    3. Save the file.

  2. Integrate the formatMessage function into your component.

    1. Import the useMemo hook from React if you haven’t already:

      import React, { useMemo } from 'react';
    2. Import the getService util function. [NOTE: The path to import getService depends on your folder structure. Make sure to adjust the import path according to your project's folder structure]:

      import getService from '../react-components/utils/angular-utils';
    3. Define the formatMessage function using useMemo:

  3. Use the formatMessage function to get translations in your JSX.

    1. Within your React component’s JSX, use the formatMessage function to get the translations:

  4. Pass parameters to the translation.

    1. If your translation message contains placeholders for dynamic content, you can pass an object with parameters to the formatMessage function:

    2. If a parameter is missing, there will be a placeholder labeled MISSING_PARAM. It ensures that all parameters are provided accurately.

    3. If a translation key isn’t found, the key itself will be displayed and an accurate error will be logged in the console. Ensure to handle these cases appropriately during the development.

OpenLMIS: the global initiative for powerful LMIS software