-
Notifications
You must be signed in to change notification settings - Fork 2
Localization module
Dmitry Usik edited this page Apr 3, 2022
·
19 revisions
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.
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:
- The files with translations should be kept in
JSONformat; - They should be named using language tags, e.g.
en.json; - Try to use
camelCasefor the keys, e.g."userName": "User name". In the future, it'll be easier to use dynamic translations.
Basically, there are 2 ways, how to use translated strings:
- If you would like to use a translated string internally in the component then your choice will be the
useTranslationhook. 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');- For the other places, where static translated strings are used, your choice will be the
I18nobject:
import { I18n } from '~modules/localization';
const someString = I18n.t('userName');If you would like to add a new language to the application, then you need to follow the next steps:
- 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;
- Import the newly created file and add it to the
translationsobject, by the example in index.ts.