DocsReact Native

@generic-translation/react-native reference

GenericTranslationProvider props, translation sources, LocaleSelector, RTL, Intl on Hermes and what was and was not verified.

On this page

Generic Translation for React Native and Expo: the same <T> / useGenericTranslation() API as @generic-translation/react, with a provider made for native. There is no DOM, cookie or document; the locale is saved in AsyncStorage, the device language picks the first locale, and translations are bundled JSON or come from the Generic Translation CDN with an offline cache. Source: generic-translation/generic-translation-react-native. See the quickstart first.

Not on npm yet, and not run on a device. Clone generic-translation/generic-translation with --recurse-submodules and link the packages. This package was developed without a simulator or phone: nothing here has been launched on iOS or Android. See what was verified.

Peer dependencies: react >= 18, react-native >= 0.73. Optional peers: @react-native-async-storage/async-storage, expo-localization, react-native-localize.

The package re-exports the whole @generic-translation/react surface under the same names (T, Var, Num, Currency, DateTime, RelativeTime, Plural, Branch, useGenericTranslation, useDictionary, useLocale, useSetLocale, useLocales, useLocaleProperties, useLocaleDirection, useGenericTranslationContext, serializeChildren, localizePath), except GenericTranslationProvider and LocaleSelector, which are native implementations. T is the unmodified @generic-translation/react component, so the CLI extracts the same messages and hashes. See React components and hooks.

GenericTranslationProvider

Prop Description
defaultLocale Language of your source strings. Default "en".
locales Target locales (the default is added automatically).
locale Start in this locale and skip stored and device detection. Later changes of the prop switch locale.
translations Bundled maps { [locale]: map | () => map | Promise<map> }. A module namespace { default: map } is unwrapped.
loadTranslations (locale) => map | Promise<map>; replaces the bundled and CDN sources.
projectId, baseUrl, fetch Load maps from the Generic Translation CDN.
storage { getItem, setItem, removeItem? }, sync or async (AsyncStorage-compatible). Default: AsyncStorage when installed, otherwise in memory.
storageKey, cachePrefix Keys used in storage ("generic-translation-locale", "generic-translation-translations:").
getDeviceLocales () => string[] | Promise<string[]>. Default: expo-localization, else react-native-localize, else Intl.DateTimeFormat().resolvedOptions().locale.
fallback Rendered until the initial locale and translations are resolved. Default: nothing (keep your splash screen up).
dictionary Nested dictionary for useDictionary().
onLocaleChange Called after the locale is applied, including the initial resolution.
applyRTL, onRTLChange See RTL.
onError Receives load and refresh failures (default console.warn). Nothing in the provider throws.
initialLoadTimeoutMs Stop waiting for the first translations after this long and render source text. Default 5000.
devApiKey Development only, as in @generic-translation/react.

At startup the locale is, in order: the locale prop, the stored choice, the device languages (best match, so es-MX finds es), then defaultLocale. A locale is stored only when the user switches, so people who follow the system language keep following it. setLocale(locale) negotiates the locale, loads its map before switching (the old language stays visible and isLoading is true meanwhile), persists the choice and calls onLocaleChange. Unknown locales are ignored. Changing the system language while the app runs is not observed; it is picked up at the next launch.

Translation sources

  1. loadTranslations, if given, is used as is.
  2. Otherwise the bundled translations[locale] is the base.
  3. With projectId, the map saved on the device from the last CDN fetch is layered over the bundle and a CDN request starts in the background (stale-while-revalidate). The UI renders at once from bundle or cache; the fresh map re-renders and is saved for the next launch. With neither bundle nor cache the first launch waits for the network, bounded by initialLoadTimeoutMs; offline it shows source text. A failed refresh keeps what you have.

T with Text

<T> uses no DOM API. It serializes its children into an ICU message, looks the hash up, and renders strings and cloned elements back. Put it inside a <Text>, or around <Text> elements that are themselves inside a parent <Text>. Nested <Text> elements become numbered tags (Hello <0>world</0>, <1>friend</1>!) that a translator may reorder, and each keeps its own style and onPress.

LocaleSelector

Built from View, Text, Pressable, ScrollView and Modal only. Each language is shown in its own name.

  • variant="inline" (default): a wrapping row of radio buttons in a radiogroup.
  • variant="modal": a button opening a sheet with the same radios and a close button (closeLabel).

Props: locales, names, showEmoji, accessibilityLabel, closeLabel, onChange, style, itemStyle, selectedItemStyle, textStyle, selectedTextStyle, testID. Touch targets are at least 44 by 44. These accessibility roles and states are set in code and tested against mocks; they have not been tried with VoiceOver or TalkBack.

RTL

useLocaleDirection() returns "ltr" or "rtl". Native layout direction is global and React Native applies a change only after a reload, so applying it is opt-in:

<GenericTranslationProvider applyRTL onRTLChange={({ needsReload }) => needsReload && askUserToRestart()} …>

On every locale change (and at startup) I18nManager.allowRTL(true) is called, and I18nManager.forceRTL(isRtlLocale) when the direction differs. useRTLReloadNeeded() is true while a restart is pending; reload with expo-updates, react-native-restart, or ask the user. The standalone applyRTL(locale) does the same imperatively and returns { direction, isRTL, needsReload }.

Intl on Hermes

@generic-translation/core formats with Intl (PluralRules, NumberFormat, DateTimeFormat, RelativeTimeFormat, ListFormat, DisplayNames, Locale). Hermes’s ECMA-402 coverage is partial and differs between Android and iOS. Hermes’s own documentation lists Collator, DateTimeFormat, NumberFormat and getCanonicalLocales, and FormatJS’s guide reports PluralRules in recent builds and RelativeTimeFormat, ListFormat and DisplayNames as missing. No per-version table is given here because it could not be verified. Run checkIntlSupport() on your target devices:

import { checkIntlSupport } from "@generic-translation/react-native";

const intl = checkIntlSupport({ locales: ["es", "ar"] });
// { ok, missing: ["Locale", "ListFormat", …], supported: {…}, unsupportedLocales: { PluralRules: ["ar"] }, hermes: true }
if (!intl.ok) console.warn("Missing Intl features:", intl.missing);

It probes each API with a real call, not just typeof, and with locales reports locales a feature has no data for.

Polyfills

@generic-translation/react-native/polyfills is a side-effect import that, for each missing feature, loads the matching @formatjs/intl-* polyfill only if you installed it (no hard dependency):

// index.js, before anything else
import "@generic-translation/react-native/polyfills";
pnpm add @formatjs/intl-getcanonicallocales @formatjs/intl-locale @formatjs/intl-pluralrules \
  @formatjs/intl-numberformat @formatjs/intl-datetimeformat @formatjs/intl-relativetimeformat \
  @formatjs/intl-listformat @formatjs/intl-displaynames

FormatJS polyfills also need locale data per language, as static imports you add yourself because Metro cannot resolve dynamic ones, for example import "@formatjs/intl-pluralrules/locale-data/es";, one per feature per language you ship. installIntlPolyfills() returns { loaded, notInstalled, alreadySupported } so you can log what is still missing.

Metro and optional dependencies

AsyncStorage, expo-localization and react-native-localize are loaded with literal require() calls inside try blocks. Metro handles that with resolver.allowOptionalDependencies = true, the default in the Expo and React Native CLI configs. The package’s exports map the react-native condition to the CommonJS build so those require calls survive bundling. With a custom resolver that ignores export conditions, pass storage and getDeviceLocales explicitly; nothing is then auto-detected.

Other exports

createMemoryStorage(), detectStorage(), detectDeviceLocales(), intlLocales(), loadLocaleMap(), cacheKey(), applyRTL(), useRTLReloadNeeded(), and the types GenericTranslationProviderProps, LocaleSelectorProps, StorageAdapter, GetDeviceLocales, BundledTranslations, TranslationMap, RTLResult, IntlSupport.

What was verified

  • 38 unit tests (vitest and react-test-renderer, with react-native mocked): provider startup, bundled map shapes, setLocale, <T> with nested <Text> including reordered tags, CDN cache and stale-while-revalidate with a fake fetch, storage and device detection with fake modules, RTL calls and needsReload, checkIntlSupport against stubbed Intl, polyfill loading, and LocaleSelector roles and modal.
  • The example Expo app type-checks and bundles with Metro for Android (expo export, Hermes bytecode), which shows the optional-dependency requires and the linked-package setup resolve.
  • Not verified: running on an iOS or Android simulator or device; real AsyncStorage, expo-localization or react-native-localize behavior (only fakes in tests); real I18nManager reload behavior; VoiceOver and TalkBack; which Intl APIs a given Hermes build provides; the iOS bundle; React Native versions other than 0.79; and the New Architecture.

Design notes

GenericTranslationProvider wraps the @generic-translation/react provider with client-side detection turned off and replaces setLocale through the shared context. It renders fallback (default nothing) until the initial locale is resolved, to avoid a flash of source text. Metro uses the CommonJS build; the ESM build is for Node and test tooling.

Something wrong or unclear on this page? Open an issue.

Type to search the documentation.