Security News
Maven Central Adds Sigstore Signature Validation
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.
react-native-localize
Advanced tools
The react-native-localize package provides localization utilities for React Native applications. It helps in handling various localization tasks such as determining the user's locale, timezone, and country, as well as formatting numbers, dates, and times according to the user's locale.
Get User's Locale
This feature allows you to get the list of locales preferred by the user. The code sample retrieves the user's preferred locales and logs them to the console.
const { getLocales } = require('react-native-localize');
const locales = getLocales();
console.log(locales);
Get User's Timezone
This feature allows you to get the user's current timezone. The code sample retrieves the user's timezone and logs it to the console.
const { getTimeZone } = require('react-native-localize');
const timeZone = getTimeZone();
console.log(timeZone);
Get User's Country
This feature allows you to get the user's current country. The code sample retrieves the user's country and logs it to the console.
const { getCountry } = require('react-native-localize');
const country = getCountry();
console.log(country);
Format Number
This feature allows you to get the number formatting settings for the user's locale. The code sample retrieves the decimal and grouping separators and logs them to the console.
const { getNumberFormatSettings } = require('react-native-localize');
const { decimalSeparator, groupingSeparator } = getNumberFormatSettings();
console.log(`Decimal Separator: ${decimalSeparator}, Grouping Separator: ${groupingSeparator}`);
Handle Localization Changes
This feature allows you to handle changes in localization settings. The code sample adds an event listener that logs a message when localization settings change.
const { addEventListener, removeEventListener } = require('react-native-localize');
const handleLocalizationChange = () => {
console.log('Localization settings changed');
};
addEventListener('change', handleLocalizationChange);
// To remove the listener
// removeEventListener('change', handleLocalizationChange);
i18next is a popular internationalization framework for JavaScript that provides a complete solution for localizing your app. It supports multiple languages, pluralization, and interpolation. Compared to react-native-localize, i18next offers more comprehensive internationalization features but requires more setup.
react-intl is a library for internationalizing React applications. It provides components and an API to format dates, numbers, and strings, and to handle pluralization. While react-intl focuses on formatting and message handling, react-native-localize provides more utilities for determining the user's locale and timezone.
expo-localization is a package from the Expo ecosystem that provides localization utilities similar to react-native-localize. It can determine the user's locale, timezone, and country. However, expo-localization is designed to work seamlessly with Expo projects, whereas react-native-localize can be used in any React Native project.
A toolbox for your React Native app localization.
package name | version | react-native version |
---|---|---|
react-native-localize | 2.0.0+ | 0.60.0+ |
react-native-localize | 1.0.0+ | 0.56.0+ |
$ npm install --save react-native-localize
# --- or ---
$ yarn add react-native-localize
Don't forget to run pod install
after that !
Because this package targets React Native 0.60.0+, you will probably don't need to link it manually. Otherwise if it's not the case, follow this additional instructions:
Add this line to your ios/Podfile
file, then run pod install
.
target 'YourAwesomeProject' do
# …
pod 'RNLocalize', :path => '../node_modules/react-native-localize'
end
android/settings.gradle
:include ':react-native-localize'
project(':react-native-localize').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-localize/android')
android/app/build.gradle
:dependencies {
// ...
implementation project(':react-native-localize')
}
MainApplication.java
:import com.zoontek.rnlocalize.RNLocalizePackage; // <- add the RNLocalizePackage import
public class MainApplication extends Application implements ReactApplication {
// …
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// …
packages.add(new RNLocalizePackage());
return packages;
}
// …
}
Because this RNW package targets React Native 0.63.0+, you probably won't need to link it manually. Otherwise if it's not the case, follow these additional instructions. You also need to manually link the module on Windows when using React Native Windows prior to 0.63:
For more information about autolinking and manual linking. Follow the official guide
This package supports react-native-web
. Follow their official guide to configure webpack
.
import * as RNLocalize from "react-native-localize";
console.log(RNLocalize.getLocales());
console.log(RNLocalize.getCurrencies());
RNLocalize.addEventListener("change", () => {
// do localization related stuff…
});
Returns the user preferred locales, in order.
type getLocales = () => Array<{
languageCode: string;
scriptCode?: string;
countryCode: string;
languageTag: string;
isRTL: boolean;
}>;
console.log(RNLocalize.getLocales());
/* -> [
{ countryCode: "GB", languageTag: "en-GB", languageCode: "en", isRTL: false },
{ countryCode: "US", languageTag: "en-US", languageCode: "en", isRTL: false },
{ countryCode: "FR", languageTag: "fr-FR", languageCode: "fr", isRTL: false },
] */
Returns number formatting settings.
type getNumberFormatSettings = () => {
decimalSeparator: string;
groupingSeparator: string;
};
console.log(RNLocalize.getNumberFormatSettings());
/* -> {
decimalSeparator: ".",
groupingSeparator: ",",
} */
Returns the user preferred currency codes, in order.
type getCurrencies = () => Array<string>;
console.log(RNLocalize.getCurrencies());
// -> ["EUR", "GBP", "USD"]
Returns the user current country code (based on its device locale, not on its position).
type getCountry = () => string;
console.log(RNLocalize.getCountry());
// -> "FR"
Devices using Latin American regional settings will return "UN" instead of "419", as the latter is not a standard country code.
Returns the user preferred calendar format.
type getCalendar = () => "gregorian" | "japanese" | "buddhist";
console.log(RNLocalize.getCalendar());
// -> "gregorian"
Returns the user preferred temperature unit.
type getTemperatureUnit = () => "celsius" | "fahrenheit";
console.log(RNLocalize.getTemperatureUnit());
// -> "celsius"
Returns the user preferred timezone (based on its device settings, not on its position).
type getTimeZone = () => string;
console.log(RNLocalize.getTimeZone());
// -> "Europe/Paris"
Returns true
if the user prefers 24h clock format, false
if he prefers 12h clock format.
type uses24HourClock = () => boolean;
console.log(RNLocalize.uses24HourClock());
// -> true
Returns true
if the user prefers metric measure system, false
if he prefers imperial.
type usesMetricSystem = () => boolean;
console.log(RNLocalize.usesMetricSystem());
// -> true
Tells if the automatic date & time setting is enabled on the phone. Android only
type Option<T> = T | undefined;
type usesAutoDateAndTime = () => Option<boolean>;
console.log(RNLocalize.usesAutoDateAndTime()); // true or false
Tells if the automatic time zone setting is enabled on the phone. Android only
type Option<T> = T | undefined;
type usesAutoTimeZone = () => Option<boolean>;
console.log(RNLocalize.usesAutoTimeZone());
Allows you to listen for any localization change.
type addEventListener = (type: "change", handler: Function) => void;
type removeEventListener = (type: "change", handler: Function) => void;
function handleLocalizationChange() {
console.log(RNLocalize.getLocales());
}
RNLocalize.addEventListener("change", handleLocalizationChange);
// …later (ex: component unmount)
RNLocalize.removeEventListener("change", handleLocalizationChange);
Returns the best language tag possible and its reading direction (⚠️ it respects the user preferred languages list order, see explanations). Useful to pick the best translation available.
type findBestAvailableLanguage = (
languageTags: Array<string>,
) => { languageTag: string; isRTL: boolean } | void;
console.log(RNLocalize.findBestAvailableLanguage(["en-US", "en", "fr"]));
// -> { languageTag: "en-US", isRTL: false }
Browse the files in the /example directory.
Because it's a native module, you might need to mock this package to run your tests flawlessly.
Here is an example for Jest, adapt it to your needs :
// __mocks__/react-native-localize.js
const getLocales = () => [
// you can choose / add the locales you want
{ countryCode: "US", languageTag: "en-US", languageCode: "en", isRTL: false },
{ countryCode: "FR", languageTag: "fr-FR", languageCode: "fr", isRTL: false },
];
// use a provided translation, or return undefined to test your fallback
const findBestAvailableLanguage = () => ({
languageTag: "en-US",
isRTL: false,
});
const getNumberFormatSettings = () => ({
decimalSeparator: ".",
groupingSeparator: ",",
});
const getCalendar = () => "gregorian"; // or "japanese", "buddhist"
const getCountry = () => "US"; // the country code you want
const getCurrencies = () => ["USD", "EUR"]; // can be empty array
const getTemperatureUnit = () => "celsius"; // or "fahrenheit"
const getTimeZone = () => "Europe/Paris"; // the timezone you want
const uses24HourClock = () => true;
const usesMetricSystem = () => true;
const addEventListener = jest.fn();
const removeEventListener = jest.fn();
export {
findBestAvailableLanguage,
getLocales,
getNumberFormatSettings,
getCalendar,
getCountry,
getCurrencies,
getTemperatureUnit,
getTimeZone,
uses24HourClock,
usesMetricSystem,
addEventListener,
removeEventListener,
};
FAQs
A toolbox for your React Native app localization.
The npm package react-native-localize receives a total of 0 weekly downloads. As such, react-native-localize popularity was classified as not popular.
We found that react-native-localize demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.
Security News
CISOs are racing to adopt AI for cybersecurity, but hurdles in budgets and governance may leave some falling behind in the fight against cyber threats.
Research
Security News
Socket researchers uncovered a backdoored typosquat of BoltDB in the Go ecosystem, exploiting Go Module Proxy caching to persist undetected for years.