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
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:
| Prop | Type | Description |
|---|---|---|
ns? | string | string[] | Namespace or namespaces, passed to react-i18next. Default namespace: app. |
Returns:
| Prop | Type | Description |
|---|---|---|
t | TFunction | Translates a key. The second argument is the fallback text. |
i18n | i18n | The shared i18next instance. |
ready | boolean | Whether translations are loaded. |
locale | string | Current language code, such as "ar" or "en". |
direction | "ltr" | "rtl" | Text direction of the language. |
isRTL | boolean | true for right-to-left languages. |
isLTR | boolean | true for left-to-right languages. |
languageName | string | Display name of the language. |
Gotchas
- It wraps
useTranslationfrom react-i18next and adds the language fields, sotbehaves as it does in that library. - Keys come from the platform's translations and from your theme's
locales/<lang>.jsonfiles. Theme keys are merged into thethemenamespace. - 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
- Add translation keys adds your own strings step by step.
- Languages and RTL covers direction and layout.
useThemealso returnsisRTL.