Skip to content

Code Review Comments Typescript

James Brunskill edited this page Mar 29, 2023 · 17 revisions

useTranslation() doesn't need to include common

When using the useTranslation() webhook, you don't need to include the common translation file as it is included by default.

Prefer `const t = useTranslation('distribution');

Rather than

const t = useTranslation(['distribution','common']);

useTranslation() with multiple translation files (namespaces)

We're using react-i18next for localisations. Collections of translatable items are grouped into namespaces so that we can reduce bundle sizes and keep files contained to specific areas. The namespace files are json files - kept separate from the main bundles and downloaded on demand. These are also cached locally in the browser.

When using translations in your code, you may need to specify the namespace to use e.g.

import { useTranslation } from '@openmsupply-client/common';

...

const t = useTranslation('distribution');

...
<ModalLabel label={t('label.item-name')} />

You can specify multiple namespaces when using the hook:

  const t = useTranslation([ 'distribution', 'app']);

the t function will be set to first namespace as default

const { t, i18n } = useTranslation(['distribution', 'app', 'someothernamespace']);
t('button.add-item'); // This will use the distribution.json translation
t('button.open-the-menu', { ns: 'app' }); // This will use the app.json translation

the common namespace is always included as a fallback option, so you do not need to specify it as a namespace const t = useTranslation();

useTranslation() with plurals

When translating strings, it's common to need a singular and plural option. This can be accomplished using a _one and _other suffix on the translation key and passing a parameter to the translation request called 'count'.

Example

common.json

{
  "permissions_one": "Permission",
  "permissions_other": "Permissions"
}

example.ts

const t = useTranslation();

let permissionList = ['Permission a'];

let translation = t("permissions", {count: permissionList.length});
// translation will contain 'Permission' 

let permissionList = ['Permission a', 'Permission b'];

let translation = t("permissions", {count: permissionList.length});
// translation will now contain 'Permissions'