0
# Platform Utilities
1
2
Platform-specific functionality including settings access, testing utilities, and development tools for React Native localization.
3
4
## Capabilities
5
6
### Open App Language Settings
7
8
Opens the device's language settings specifically for your app (Android 13+ only).
9
10
```typescript { .api }
11
/**
12
* Open device language settings for the current app
13
* @returns Promise that resolves when settings are opened
14
* @throws Error on unsupported platforms or versions
15
*/
16
function openAppLanguageSettings(): Promise<void>;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { openAppLanguageSettings } from "react-native-localize";
23
24
// Basic usage
25
async function openLanguageSettings() {
26
try {
27
await openAppLanguageSettings();
28
console.log("Language settings opened");
29
} catch (error) {
30
console.log("Cannot open language settings:", error.message);
31
// Fallback: open general system settings or show instructions
32
}
33
}
34
35
// With user interaction
36
function LanguageSettingsButton() {
37
const handlePress = async () => {
38
try {
39
await openAppLanguageSettings();
40
} catch (error) {
41
// Show fallback UI for unsupported platforms
42
Alert.alert(
43
"Language Settings",
44
"Please change your app language in system settings:\nSettings > Apps > [Your App] > Language",
45
[{ text: "OK" }]
46
);
47
}
48
};
49
50
return (
51
<Button title="Change App Language" onPress={handlePress} />
52
);
53
}
54
```
55
56
**Platform-Aware Implementation:**
57
58
```typescript
59
import { Platform } from "react-native";
60
import { openAppLanguageSettings } from "react-native-localize";
61
62
async function showLanguageOptions() {
63
if (Platform.OS === "android") {
64
try {
65
// Try to open per-app language settings (Android 13+)
66
await openAppLanguageSettings();
67
} catch (error) {
68
// Fallback for older Android versions
69
showCustomLanguagePicker();
70
}
71
} else {
72
// iOS doesn't support per-app language settings via this API
73
showCustomLanguagePicker();
74
}
75
}
76
77
function showCustomLanguagePicker() {
78
// Show in-app language selection
79
const supportedLanguages = ["en", "es", "fr", "de"];
80
// ... implement custom language picker
81
}
82
```
83
84
## Testing and Development Utilities
85
86
### Mock Support
87
88
React Native Localize provides comprehensive mock utilities for testing and development.
89
90
#### Basic Mock Usage
91
92
```typescript
93
// In your test setup or development environment
94
import * as RNLocalize from "react-native-localize";
95
96
// Mock specific functions
97
jest.mock("react-native-localize", () => ({
98
getLocales: () => [
99
{ languageCode: "en", countryCode: "US", languageTag: "en-US", isRTL: false },
100
{ languageCode: "es", countryCode: "US", languageTag: "es-US", isRTL: false }
101
],
102
getCountry: () => "US",
103
getCurrencies: () => ["USD"],
104
getTemperatureUnit: () => "fahrenheit",
105
uses24HourClock: () => false,
106
usesMetricSystem: () => false,
107
findBestLanguageTag: (tags) => ({ languageTag: tags[0], isRTL: false })
108
}));
109
```
110
111
#### Using Built-in Mocks
112
113
```typescript
114
// Use the provided mock functions
115
import * as MockRNLocalize from "react-native-localize/mock";
116
117
describe("Localization tests", () => {
118
beforeEach(() => {
119
// Reset mocks to default values
120
jest.resetModules();
121
});
122
123
test("should format temperature correctly", () => {
124
// Mock returns "celsius" by default
125
const temp = formatTemperature(25);
126
expect(temp).toBe("25°C");
127
});
128
129
test("should handle US locale", () => {
130
// Mock returns US locale by default
131
const country = MockRNLocalize.getCountry();
132
expect(country).toBe("US");
133
});
134
});
135
```
136
137
#### Jest Integration
138
139
```typescript
140
// Use Jest-wrapped mocks for more control
141
import * as RNLocalizeJest from "react-native-localize/mock/jest";
142
143
describe("Language selection", () => {
144
test("should select best language", () => {
145
// Mock returns en-US by default
146
const result = RNLocalizeJest.findBestLanguageTag(["en-US", "fr-FR"]);
147
expect(result).toEqual({ languageTag: "en-US", isRTL: false });
148
149
// Verify the mock was called
150
expect(RNLocalizeJest.findBestLanguageTag).toHaveBeenCalledWith(["en-US", "fr-FR"]);
151
});
152
});
153
```
154
155
### Custom Mock Configuration
156
157
```typescript
158
// Create custom mock configurations for different test scenarios
159
const createMockConfig = (overrides = {}) => ({
160
getLocales: () => [
161
{ languageCode: "en", countryCode: "US", languageTag: "en-US", isRTL: false }
162
],
163
getCountry: () => "US",
164
getCurrencies: () => ["USD"],
165
getTemperatureUnit: () => "fahrenheit",
166
uses24HourClock: () => false,
167
usesMetricSystem: () => false,
168
getNumberFormatSettings: () => ({ decimalSeparator: ".", groupingSeparator: "," }),
169
...overrides
170
});
171
172
// Test with European locale
173
const europeanMock = createMockConfig({
174
getLocales: () => [
175
{ languageCode: "fr", countryCode: "FR", languageTag: "fr-FR", isRTL: false }
176
],
177
getCountry: () => "FR",
178
getCurrencies: () => ["EUR"],
179
getTemperatureUnit: () => "celsius",
180
uses24HourClock: () => true,
181
usesMetricSystem: () => true,
182
getNumberFormatSettings: () => ({ decimalSeparator: ",", groupingSeparator: " " })
183
});
184
185
// Test with RTL locale
186
const rtlMock = createMockConfig({
187
getLocales: () => [
188
{ languageCode: "ar", countryCode: "SA", languageTag: "ar-SA", isRTL: true }
189
],
190
getCountry: () => "SA",
191
findBestLanguageTag: (tags) => ({ languageTag: tags[0], isRTL: true })
192
});
193
```
194
195
## Expo Plugin Integration
196
197
### Expo Configuration
198
199
React Native Localize includes an Expo plugin for configuring supported locales in your app.
200
201
```javascript
202
// app.config.js or expo.json
203
module.exports = {
204
plugins: [
205
[
206
"react-native-localize",
207
{
208
locales: ["en", "es", "fr", "de"] // Supported locales
209
}
210
]
211
]
212
};
213
214
// Platform-specific locale configuration
215
module.exports = {
216
plugins: [
217
[
218
"react-native-localize",
219
{
220
locales: {
221
ios: ["en", "es", "fr"],
222
android: ["en", "es", "fr", "de"]
223
}
224
}
225
]
226
]
227
};
228
```
229
230
The Expo plugin automatically:
231
- Configures iOS `CFBundleLocalizations` in Info.plist
232
- Sets up Android locale configuration files
233
- Configures Android resource filtering for supported locales
234
235
### Development Tools
236
237
```typescript
238
// Development helper to log all locale information
239
function logLocaleInfo() {
240
console.log("=== Device Locale Information ===");
241
console.log("Locales:", getLocales());
242
console.log("Country:", getCountry());
243
console.log("Currencies:", getCurrencies());
244
console.log("Temperature unit:", getTemperatureUnit());
245
console.log("24-hour clock:", uses24HourClock());
246
console.log("Metric system:", usesMetricSystem());
247
console.log("Number format:", getNumberFormatSettings());
248
console.log("Timezone:", getTimeZone());
249
console.log("Calendar:", getCalendar());
250
251
const autoSettings = {
252
autoDateTime: usesAutoDateAndTime(),
253
autoTimezone: usesAutoTimeZone()
254
};
255
console.log("Auto settings:", autoSettings);
256
}
257
258
// Test language matching
259
function testLanguageMatching() {
260
const supportedLanguages = ["en-US", "es-ES", "fr-FR", "de-DE", "ar-SA"];
261
const match = findBestLanguageTag(supportedLanguages);
262
console.log("Best language match:", match);
263
}
264
```
265
266
## Error Handling
267
268
```typescript
269
import { openAppLanguageSettings } from "react-native-localize";
270
271
// Comprehensive error handling for platform utilities
272
async function safeOpenLanguageSettings(): Promise<boolean> {
273
try {
274
await openAppLanguageSettings();
275
return true;
276
} catch (error) {
277
if (error.message.includes("supported only on Android 13+")) {
278
console.log("Per-app language settings not available on this platform");
279
} else {
280
console.error("Failed to open language settings:", error);
281
}
282
return false;
283
}
284
}
285
286
// Usage with user feedback
287
async function handleLanguageSettingsRequest() {
288
const opened = await safeOpenLanguageSettings();
289
290
if (!opened) {
291
// Show alternative options
292
showInAppLanguageSelector();
293
}
294
}
295
```