Something similar to [NSLocale currentLocale] in Objective-C.
I am using react-native-i18n
in order to access the device's language I used:
import { getLanguages } from 'react-native-i18n';
getLanguages().then(languages => {
console.log(languages); // ['en-US', 'en']
});
It's all in the documentation.
This code is future proof
import {NativeModules} from 'react-native';
function getSystemLocale(): string {
let locale: string;
// iOS
if (
NativeModules.SettingsManager &&
NativeModules.SettingsManager.settings &&
NativeModules.SettingsManager.settings.AppleLanguages
) {
locale = NativeModules.SettingsManager.settings.AppleLanguages[0];
// Android
} else if (NativeModules.I18nManager) {
locale = NativeModules.I18nManager.localeIdentifier;
}
if (typeof locale === 'undefined') {
console.log('Couldnt get locale');
return 'en';
}
return locale;
}
export default {
getSystemLocale,
};
function getLocale() {
if (React.Platform.OS === 'android') {
return I18n.locale;
} else {
return NativeModules.SettingsManager.settings.AppleLocale.replace(/_/, '-');
}
}
NativeModules solution can be changed over time by Facebook developers.
Because of this reason I had prepared a component. (It works only on Android for now)
Sample usage:
import SystemSettings from 'react-native-system-settings'
SystemSettings.get(
settings => console.log('settings: ', settings)
)
Also promise-then can be used:
SystemSettings.get().then(settings => console.log('settings: ', settings)).done()
Also ES7 async-await method can be used!
class App extends React.Component {
componentWillMount() {
this._loadInitialState()
}
_loadInitialState = async () => {
try {
let settings = await SystemSettings.get()
// Now settings variable would be filled and can be used!
} catch (error) {}
};
}
A sample result:
{
densityDpi: 320,
fontScale: 1,
hardKeyboardHidden: "no",
keyboard: "qwerty",
keyboardHidden: "no",
localization: {
country: "US",
displayCountry: "United States",
displayLanguage: "English",
displayName: "English (United States)",
is24HourFormat: false,
language: "en",
locale: "en_US",
networkCountry: "US",
simCountry: "US",
timeZone: {
ID: "Europe/Amsterdam",
displayName: {
long: "Amsterdam Standard Time",
short: "GMT+01:00",
},
offset: 3600000
}
},
orientation: "portrait",
screenHeightDp: 615,
screenLayout: "normal",
screenWidthDp: 360,
smallestScreenWidthDp: 360,
uiModeType: "normal"
}
I am using the i18n package (react-native-i18n). And then it's just:
I18n = require('react-native-i18n')
locale = I18n.currentLocale()
Personally I prefer use react-native-i18n. then you can use like this inside the documentation..
import { getLanguages } from 'react-native-i18n'
getLanguages().then(languages => {
console.log(languages) // ['en-US', 'en']
})
link: https://github.com/AlexanderZaytsev/react-native-i18n