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
Create keys in
messages_en.json
:Open your
messages_en.json
file.Add the translation keys along with their respective messages:
{ "translationKey": "Translation Key", "translationKey.withParams": "Translation Key ${id}" }
Save the file.
Integrate the
formatMessage
function into your component.Import the
useMemo
hook from React if you haven’t already:import React, { useMemo } from 'react';
Import the
getService
util function. [NOTE: The path to importgetService
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';
Define the
formatMessage
function usinguseMemo
:
Use the
formatMessage
function to get translations in your JSX.Within your React component’s JSX, use the
formatMessage
function to get the translations:
Pass parameters to the translation.
If your translation message contains placeholders for dynamic content, you can pass an object with parameters to the
formatMessage
function:If a parameter is missing, there will be a placeholder labeled MISSING_PARAM. It ensures that all parameters are provided accurately.
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