Skip to main content

Translations (i18n) in React

Internationalisation (or i18n for short) is the concept of adapting a website for another country, language or culture. It regroups the translations of text, but also the format of dates and hours for example.

Translating texts

In the front end, we use the i18next library to make translations. To use it, just call the useTranslation hook in your component and then use it to call a key:

// do not use { useTranslation } from 'react-i18next'!!!
import { useTranslation } from '#shared/i18n/useTranslation';

function HomePage(): JSX.Element {
const { t } = useTranslation();
const myName = 'John';

return <p>{t('home.welcome', { firstName: myName })}</p>;
}

Then, add your translations in the frontend/src/translations/<lang>.json files:

// fr-FR.json
{
"home": {
"welcome": "Bienvenue {{firstName}} !"
}
}

If you need to pass a React component inside your text (like a Link), you can also use the <Trans> component.

Formatting dates

To format a date, use the method formatDate(date: Date, options: Intl.DateTimeFormatOptions) of the useTranslation hook:

import { useTranslation } from '#shared/i18n/useTranslation';

function MyComponent(): JSX.Element {
const { formatDate } = useTranslation();
const today = new Date(); // get the date of today

return <p>{formatDate(today, { dateStyle: 'long' })}</p>;
}

// returns "17 février 2023"

The available options for formatting are listed here: DateTimeFormatOptions.

Formatting numbers

There are also a method formatNumber in the hook that you can use, to format number with units, currency, or as ordinals (first, second, etc...). See the MDN reference for the options here: NumberFormatOptions.

Adding a new locale

Find the locale code

The code of a locale is defined in 2 parts:

  • the language (e.g fr, en...): it defines which translations to use;
  • the region code (e.g. FR, US, GB): it defines the date and number formatting which will be used.
  1. Create a new file in frontend/src/translations/<lang>.json with the international code of the language (e.g. fr-FR.json for French). Make a copy of one of the existing file and translate all texts.
  2. In src/shared/i18n/config.ts:
    • Add the language code in the languages array:
      export const languages = ['fr-FR', 'en-GB', 'en-US'] as const;
    • Import the JSON file:
      import translationFr from './fr-FR.json';
    • Add it to the resources key:
      resources: {
      "fr-FR": { translation: translationFr },
      },
  3. In src/shared/i18n/useTranslation.ts, import the locale from date-fns and map it to the language previously defined in the languages array.
  4. In src/theme.ts, import the locale from @mui/x-date-pickers and map it again to the same language.
  5. In src/shared/ckeditor/getCKEditorLanguage.ts, map again the language to a CKEditor language.
  6. Finally, in vite.config.ts, declare the ckeditor language to import in the ckeditor5() function from the CKEditor5 plugin.