Skip to content

Localization module

Dmitry Usik edited this page Apr 3, 2022 · 19 revisions

🤔 Intro

Even if your application supports only 1 language, it's a good practice to lay the architecture out for localization in the very beginning. Then in the future, if another language should be supported you'll just have to add one more JSON file with translations.

🏴󠁧󠁢󠁥󠁮󠁧󠁿 Translations

Try to follow the next rules, but remember, that some of them might be changed or improved for the specific project, based on the internal discussions:

  1. The files with translations should be kept in JSON format;
  2. They should be named using language tags, e.g. en.json;
  3. Try to use camelCase for the keys, e.g. "userName": "User name". In the future, it'll be easier to use dynamic translations.

Usage

Basically, there are 2 ways, how to use translated strings:

  1. If you would like to use a translated string internally in the component then your choice will be the useTranslation hook. It'll rerender the component if the language is changed, so the localization will be dynamic:
import { useTranslation } from 'react-i18next';
 
const { t } = useTranslation();
const someString = t('userName');
  1. For the other places, where static translated strings are used, your choice will be the I18n object:
import { I18n } from '~modules/localization';

const someString = I18n.t('userName');

🇩🇪 New language

If you would like to add a new language to the application, then you need to follow the next steps:

  1. Add a new JSON file with translated strings to localization/translations. It should be the copy of the file with the main language, so the keys should be the same, but the values should be different;
  2. Import the newly created file and add it to the translations object, by the example in index.ts.

Clone this wiki locally