Created
June 15, 2020 20:06
-
-
Save stevenselcuk/c602fccc66ee4d10abc7d0222fdf48c2 to your computer and use it in GitHub Desktop.
Snippet for React & React Native localization support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import i18n from 'i18next'; | |
| import {initReactI18next} from 'react-i18next'; | |
| import {NativeModules} from 'react-native'; | |
| import {Platform} from 'react-native'; | |
| import resources from '../translations'; | |
| function localeToLanguage(locale) { | |
| return locale.replace('_', '-'); | |
| } | |
| i18n | |
| .use({ | |
| type: 'languageDetector', | |
| async: true, | |
| init: () => {}, | |
| detect: function(callback) { | |
| /** | |
| * - https://github.com/facebook/react-native/issues/26540 | |
| * - https://stackoverflow.com/a/35493069 | |
| */ | |
| let detectedLanguage = 'en'; | |
| if (Platform.OS === 'ios') { | |
| const appleLocale = NativeModules.SettingsManager.settings.AppleLocale; | |
| if (!appleLocale) { | |
| const firstLanguage = | |
| NativeModules.SettingsManager.settings.AppleLanguages[0]; | |
| if (firstLanguage) { | |
| detectedLanguage = firstLanguage; | |
| } | |
| } else { | |
| detectedLanguage = localeToLanguage(appleLocale); | |
| } | |
| } else if (Platform.OS === 'android') { | |
| const androidLocale = NativeModules.I18nManager.localeIdentifier; | |
| if (androidLocale) { | |
| detectedLanguage = localeToLanguage(androidLocale); | |
| } | |
| } | |
| callback(detectedLanguage); | |
| }, | |
| cacheUserLanguage: () => {}, | |
| }) | |
| .use(initReactI18next) | |
| .init({ | |
| resources, | |
| fallbackLng: 'en', | |
| returnNull: false, | |
| returnEmptyString: false, | |
| interpolation: { | |
| escapeValue: false, | |
| }, | |
| }); | |
| export default i18n; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment