CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-native-localize

A toolbox for your React Native app localization.

Pending
Overview
Eval results
Files

platform-utilities.mddocs/

Platform Utilities

Platform-specific functionality including settings access, testing utilities, and development tools for React Native localization.

Capabilities

Open App Language Settings

Opens the device's language settings specifically for your app (Android 13+ only).

/**
 * Open device language settings for the current app
 * @returns Promise that resolves when settings are opened
 * @throws Error on unsupported platforms or versions
 */
function openAppLanguageSettings(): Promise<void>;

Usage Examples:

import { openAppLanguageSettings } from "react-native-localize";

// Basic usage
async function openLanguageSettings() {
  try {
    await openAppLanguageSettings();
    console.log("Language settings opened");
  } catch (error) {
    console.log("Cannot open language settings:", error.message);
    // Fallback: open general system settings or show instructions
  }
}

// With user interaction
function LanguageSettingsButton() {
  const handlePress = async () => {
    try {
      await openAppLanguageSettings();
    } catch (error) {
      // Show fallback UI for unsupported platforms
      Alert.alert(
        "Language Settings",
        "Please change your app language in system settings:\nSettings > Apps > [Your App] > Language",
        [{ text: "OK" }]
      );
    }
  };
  
  return (
    <Button title="Change App Language" onPress={handlePress} />
  );
}

Platform-Aware Implementation:

import { Platform } from "react-native";
import { openAppLanguageSettings } from "react-native-localize";

async function showLanguageOptions() {
  if (Platform.OS === "android") {
    try {
      // Try to open per-app language settings (Android 13+)
      await openAppLanguageSettings();
    } catch (error) {
      // Fallback for older Android versions
      showCustomLanguagePicker();
    }
  } else {
    // iOS doesn't support per-app language settings via this API
    showCustomLanguagePicker();
  }
}

function showCustomLanguagePicker() {
  // Show in-app language selection
  const supportedLanguages = ["en", "es", "fr", "de"];
  // ... implement custom language picker
}

Testing and Development Utilities

Mock Support

React Native Localize provides comprehensive mock utilities for testing and development.

Basic Mock Usage

// In your test setup or development environment
import * as RNLocalize from "react-native-localize";

// Mock specific functions
jest.mock("react-native-localize", () => ({
  getLocales: () => [
    { languageCode: "en", countryCode: "US", languageTag: "en-US", isRTL: false },
    { languageCode: "es", countryCode: "US", languageTag: "es-US", isRTL: false }
  ],
  getCountry: () => "US",
  getCurrencies: () => ["USD"],
  getTemperatureUnit: () => "fahrenheit",
  uses24HourClock: () => false,
  usesMetricSystem: () => false,
  findBestLanguageTag: (tags) => ({ languageTag: tags[0], isRTL: false })
}));

Using Built-in Mocks

// Use the provided mock functions
import * as MockRNLocalize from "react-native-localize/mock";

describe("Localization tests", () => {
  beforeEach(() => {
    // Reset mocks to default values
    jest.resetModules();
  });
  
  test("should format temperature correctly", () => {
    // Mock returns "celsius" by default
    const temp = formatTemperature(25);
    expect(temp).toBe("25°C");
  });
  
  test("should handle US locale", () => {
    // Mock returns US locale by default
    const country = MockRNLocalize.getCountry();
    expect(country).toBe("US");
  });
});

Jest Integration

// Use Jest-wrapped mocks for more control
import * as RNLocalizeJest from "react-native-localize/mock/jest";

describe("Language selection", () => {
  test("should select best language", () => {
    // Mock returns en-US by default
    const result = RNLocalizeJest.findBestLanguageTag(["en-US", "fr-FR"]);
    expect(result).toEqual({ languageTag: "en-US", isRTL: false });
    
    // Verify the mock was called
    expect(RNLocalizeJest.findBestLanguageTag).toHaveBeenCalledWith(["en-US", "fr-FR"]);
  });
});

Custom Mock Configuration

// Create custom mock configurations for different test scenarios
const createMockConfig = (overrides = {}) => ({
  getLocales: () => [
    { languageCode: "en", countryCode: "US", languageTag: "en-US", isRTL: false }
  ],
  getCountry: () => "US",
  getCurrencies: () => ["USD"],
  getTemperatureUnit: () => "fahrenheit",
  uses24HourClock: () => false,
  usesMetricSystem: () => false,
  getNumberFormatSettings: () => ({ decimalSeparator: ".", groupingSeparator: "," }),
  ...overrides
});

// Test with European locale
const europeanMock = createMockConfig({
  getLocales: () => [
    { languageCode: "fr", countryCode: "FR", languageTag: "fr-FR", isRTL: false }
  ],
  getCountry: () => "FR",
  getCurrencies: () => ["EUR"],
  getTemperatureUnit: () => "celsius",
  uses24HourClock: () => true,
  usesMetricSystem: () => true,
  getNumberFormatSettings: () => ({ decimalSeparator: ",", groupingSeparator: " " })
});

// Test with RTL locale
const rtlMock = createMockConfig({
  getLocales: () => [
    { languageCode: "ar", countryCode: "SA", languageTag: "ar-SA", isRTL: true }
  ],
  getCountry: () => "SA",
  findBestLanguageTag: (tags) => ({ languageTag: tags[0], isRTL: true })
});

Expo Plugin Integration

Expo Configuration

React Native Localize includes an Expo plugin for configuring supported locales in your app.

// app.config.js or expo.json
module.exports = {
  plugins: [
    [
      "react-native-localize",
      {
        locales: ["en", "es", "fr", "de"] // Supported locales
      }
    ]
  ]
};

// Platform-specific locale configuration
module.exports = {
  plugins: [
    [
      "react-native-localize", 
      {
        locales: {
          ios: ["en", "es", "fr"],
          android: ["en", "es", "fr", "de"]
        }
      }
    ]
  ]
};

The Expo plugin automatically:

  • Configures iOS CFBundleLocalizations in Info.plist
  • Sets up Android locale configuration files
  • Configures Android resource filtering for supported locales

Development Tools

// Development helper to log all locale information
function logLocaleInfo() {
  console.log("=== Device Locale Information ===");
  console.log("Locales:", getLocales());
  console.log("Country:", getCountry());
  console.log("Currencies:", getCurrencies());
  console.log("Temperature unit:", getTemperatureUnit());
  console.log("24-hour clock:", uses24HourClock());
  console.log("Metric system:", usesMetricSystem());
  console.log("Number format:", getNumberFormatSettings());
  console.log("Timezone:", getTimeZone());
  console.log("Calendar:", getCalendar());
  
  const autoSettings = {
    autoDateTime: usesAutoDateAndTime(),
    autoTimezone: usesAutoTimeZone()
  };
  console.log("Auto settings:", autoSettings);
}

// Test language matching
function testLanguageMatching() {
  const supportedLanguages = ["en-US", "es-ES", "fr-FR", "de-DE", "ar-SA"];
  const match = findBestLanguageTag(supportedLanguages);
  console.log("Best language match:", match);
}

Error Handling

import { openAppLanguageSettings } from "react-native-localize";

// Comprehensive error handling for platform utilities
async function safeOpenLanguageSettings(): Promise<boolean> {
  try {
    await openAppLanguageSettings();
    return true;
  } catch (error) {
    if (error.message.includes("supported only on Android 13+")) {
      console.log("Per-app language settings not available on this platform");
    } else {
      console.error("Failed to open language settings:", error);
    }
    return false;
  }
}

// Usage with user feedback
async function handleLanguageSettingsRequest() {
  const opened = await safeOpenLanguageSettings();
  
  if (!opened) {
    // Show alternative options
    showInAppLanguageSelector();
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-react-native-localize

docs

device-preferences.md

device-settings.md

index.md

language-matching.md

number-currency-formatting.md

platform-utilities.md

tile.json