react-native-localize

repository·master·Indexed 25 days ago

https://github.com/zoontek/react-native-localize

A toolbox for React Native app localization (version 3.7.0) used to access device information such as country, currency, calendar, and locale settings. It provides the useLocalize hook for React components, a findBestLanguageTag utility for language matching, and an Expo Config Plugin (withLocalize) to automate native configurations for iOS and Android. The library also includes a mock implementation for testing in environments where native modules are unavailable.

Tokens
2.8K
Snippets
6
Records
17
Agent score
81%

What's inside react-native-localize

  1. Configure react-native-localize with Expo via withLocalize

    master

    To use react-native-localize in an Expo project, use the withLocalize config plugin. This plugin automates the necessary native configuration for both iOS and Android to support specific locale codes.

    Configuration Options

    The plugin accepts a LocalizePluginConfig object:

    • locales: A list of supported locale codes (e.g., ["en", "fr", "zh-Hans-CN"]).
      • You can provide a single array shared by both platforms: locales: ['en', 'fr'].
      • Or provide platform-specific arrays: locales: { android: ['en'], ios: ['fr'] }.

    Platform Behavior

    • iOS: Updates CFBundleLocalizations in the Info.plist with the provided locales.
    • Android:
      • Generates a locale_config.xml file in the project resources.
      • Updates the AndroidManifest.xml to use the new android:localeConfig.
      • Modifies build.gradle to include the resourceConfigurations for the specified locales, ensuring proper resource filtering.
  2. Use the LocalizeApi interface

    master

    The LocalizeApi defines the primary methods available for accessing device localization information. Key methods include:

    • getCalendar(): Returns the current Calendar system.
    • getCountry(): Returns the ISO 3166-1 alpha-2 country code.
    • getCurrencies(): Returns an array of available currency codes.
    • getLocales(): Returns an array of Locale objects.
    • getNumberFormatSettings(): Returns NumberFormatSettings for numeric formatting.
    • getTemperatureUnit(): Returns the preferred TemperatureUnit ("celsius" | "fahrenheit").
    • getTimeZone(): Returns the device time zone string.
    • uses24HourClock(): Returns a boolean indicating if the device uses a 24-hour clock.
    • usesMetricSystem(): Returns a boolean indicating if the device uses the metric system.
    • usesAutoDateAndTime(): Returns boolean | undefined for automatic date/time settings.
    • usesAutoTimeZone(): Returns boolean | undefined for automatic time zone settings.
    • findBestLanguageTag(languageTags): Takes a readonly array of BCP 47 tags and returns the best match containing the languageTag and isRTL status, or undefined if no match is found.
    • openAppLanguageSettings(): Returns a Promise<void> that opens the device's language settings.
    export type LocalizeApi = {
      getCalendar: () => Calendar;
      getCountry: () => string;
      getCurrencies: () => string[];
      getLocales: () => Locale[];
      getNumberFormatSettings: () => NumberFormatSettings;
      getTemperatureUnit: () => TemperatureUnit;
      getTimeZone: () => string;
      uses24HourClock: () => boolean;
      usesMetricSystem: () => boolean;
      usesAutoDateAndTime: () => boolean | undefined;
      usesAutoTimeZone: () => boolean | undefined;
    
    findBestLanguageTag: <T extends string>(
        languageTags: readonly T[],
      ) => { languageTag: T; isRTL: boolean } | undefined;
    
    openAppLanguageSettings: () => Promise<void>;
    };
  3. Get device localization information with react-native-localize

    master

    The react-native-localize library provides several functions to retrieve device-specific localization settings, including country, currency, calendar, and time zone information.

    Key functions include:

    • getCountry(): Returns the ISO 3166-1 alpha-2 country code.
    • getCurrencies(): Returns an array of available currencies.
    • getCalendar(): Returns the device's calendar settings.
    • getTimeZone(): Returns the device's time zone.
    • getLocales(): Returns an array of Locale objects representing the device's language and region settings.
    • getTemperatureUnit(): Returns the device's temperature unit (TemperatureUnit).
    • getNumberFormatSettings(): Returns NumberFormatSettings for numeric formatting.
  4. Check device system settings and preferences

    master

    You can query specific system preferences to determine how the device handles time, dates, and measurements:

    • uses24HourClock(): Returns a boolean indicating if the device uses a 24-hour clock.
    • usesAutoDateAndTime(): Returns a boolean indicating if the device uses automatic date and time.
    • usesAutoTimeZone(): Returns a boolean indicating if the device uses an automatic time zone.
    • usesMetricSystem(): Returns a boolean indicating if the device uses the metric system.
  5. Use the mock implementation of react-native-localize for testing

    master

    The src/extras/mock/index.ts file provides a mock implementation of the react-native-localize API. This is useful for running tests in environments where the native modules are unavailable (like Node.js or web-based test runners) or for simulating specific localization settings.

    It exports functions that mirror the real API, such as getCalendar, getCountry, getLocales, and useLocalize hook, allowing you to mock the behavior of the library in your test suites.

  6. Reference the Locale type

    master

    The Locale type represents device locale information. It is a read-only object containing language, region, and text direction details.

    export type Locale = Readonly<{
      /** ISO 639-1 language code (e.g., `"en"`, `"fr"`, `"ar"`) */
      languageCode: string;
      /** ISO 15924 script code, if applicable (e.g., `"Hans"` for simplified Chinese) */
      scriptCode?: string;
      /** ISO 3166-1 alpha-2 country/region code (e.g., `"US"`, `"FR"`) */
      countryCode: string;
      /** Full BCP 47 language tag (e.g., `"en-US"`, `"zh-Hans-CN"`) */
      languageTag: string;
      /** Whether the locale uses right-to-left text direction */
      isRTL: boolean;
    }>
  7. Reference: LocalizePluginConfig schema

    master

    The configuration object passed to the withLocalize Expo plugin defines which locales are supported on each platform.

    type LocalizePluginConfig = {
      /**
       * List of supported locale codes (e.g. `["en", "fr", "zh-Hans-CN"]`).
       * Can be a single array shared by both platforms, or platform-specific arrays.
       */
      locales?: string[] | { android?: string[]; ios?: string[] };
    };
  8. Reference the NumberFormatSettings type

    master

    The NumberFormatSettings type defines the characters used for numeric formatting based on the device's locale.

    export type NumberFormatSettings = Readonly<{
      /** Character used as decimal separator (e.g. "." or ",") */
      decimalSeparator: string;
      /** Character used as thousands separator (e.g. "," or " ") */
      groupingSeparator: string;
    }>