Skip to content

Instantly share code, notes, and snippets.

@cayasso
Last active November 2, 2018 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cayasso/7ddb3a88dae30ab828a80c18a05b290d to your computer and use it in GitHub Desktop.
Save cayasso/7ddb3a88dae30ab828a80c18a05b290d to your computer and use it in GitHub Desktop.
i18n react native
import React from 'react'
import { Text, View } from 'react-native'
import i18n from 'lib/i18n
const name = 'Norman Ramirez'
export default () => (
<View>
<Text>{i18n`Hi how are you ${name}`}</Text>
<Text>{i18n`I am fine`}</Text>
<Text>Your locale is {i18n.locale}</Text>
</View>
)
{
"Hi how are you ${0}": "Hola como estas ${0}",
"I am fine": "Estoy bien"
}
import { Platform, NativeModules } from 'react-native'
import es from '../translations/es.json'
const init = () => {
i18n.set(getLocale())
}
const getLocale = () => {
const locale = Platform.selectt({
android: NativeModules.I18nManager.localeIdentifier,
ios: NativeModules.SettingsManager.settings.AppleLocale
})
return locale.substring(0, 2) || i18n.locale
}
const getKey = tpl => {
const key = (acc, str, i) => `${str}\${${i}}${acc}`
return tpl
.slice(0, -1)
.reduceRight(key, tpl[tpl.length - 1])
.replace(/\r\n/g, '\n')
}
const i18n = (tpl, ...values) => {
const key = getKey(tpl)
const db = (i18n.db || {})[i18n.locale] || {}
const str = db[key]
if (!str) {
const out = [tpl[0]]
for (let i = 0, l = values.length; i < l; ++i) {
out.push(values[i], tpl[i + 1])
}
return out.join('')
}
return str.replace(/\${(\d)}/g, (_, i) => values[Number(i)])
}
i18n.set = locale => {
if (!locale) return
i18n.db = i18n.db || {}
if (!i18n.db[locale]) {
i18n.db[locale] = i18n.locales[locale]
}
i18n.locale = locale
}
i18n.db = {}
i18n.locale = 'en'
i18n.locales = {
en: {},
es: es.default
}
init()
export default i18n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment