useTranslation

Translate text with a fallback and read the current language and direction.

Use useTranslation for every string a customer reads, and when a component needs to know the current language or text direction.

Example

app/components/layout/BackButton.tsx
import { useTranslation } from '@salla.sa/twilight-theme-engine/i18n';

export function BackButton() {
  const { t, isRTL } = useTranslation();
  return (
    <button aria-label={t('blocks.header.back', 'Back')}>
      <span aria-hidden="true">{isRTL ? '→' : '←'}</span>
    </button>
  );
}

t(key, fallback) returns the translation for key, or fallback when there is none.

API

function useTranslation(ns?: string | string[]): {
  t: TFunction;
  i18n: i18n;
  ready: boolean;
  locale: string;
  direction: 'ltr' | 'rtl';
  isRTL: boolean;
  isLTR: boolean;
  languageName: string;
};

Argument:

PropTypeDescription
ns?string | string[]Namespace or namespaces, passed to react-i18next. Default namespace: app.

Returns:

PropTypeDescription
tTFunctionTranslates a key. The second argument is the fallback text.
i18ni18nThe shared i18next instance.
readybooleanWhether translations are loaded.
localestringCurrent language code, such as "ar" or "en".
direction"ltr" | "rtl"Text direction of the language.
isRTLbooleantrue for right-to-left languages.
isLTRbooleantrue for left-to-right languages.
languageNamestringDisplay name of the language.

Gotchas

  • It wraps useTranslation from react-i18next and adds the language fields, so t behaves as it does in that library.
  • Keys come from the platform's translations and from your theme's locales/<lang>.json files. Theme keys are merged into the theme namespace.
  • It works during server rendering, with the language chosen for the request.
  • Outside the provider, the language fields fall back to Arabic, right to left.

Next

On this page