I am using i18n-js within my expo project to translate my app.
This is how I configure it:
import React from \'re
You need to setup the translation in your top level component, like App.js. Then, you have to create 2 json files: fr.json
and en.json
in /src/locales/
.
Finally, in any screen, you have to import i18n
and use the t()
function to translate strings.
import React, { useEffect, useState } from 'react'
import { loadLocale } from './locales/i18n'
export default function App() {
const [theme, setTheme] = useState(null)
useEffect(() => {
init()
}, [])
const init = async () => {
await loadLocale()
}
return (
)
}
import * as Localization from 'expo-localization'
import i18n from 'i18n-js'
i18n.defaultLocale = 'fr'
i18n.locale = 'fr'
i18n.fallbacks = true
export const loadLocale = async () => {
for (const locale of Localization.locales) {
if (i18n.translations[locale.languageCode] !== null) {
i18n.locale = locale.languageCode
switch (locale.languageCode) {
case 'en':
import('./en.json').then(en => {
i18n.translations = { en }
})
break
default:
case 'fr':
import('./fr.json').then(fr => {
i18n.translations = { fr }
})
break
}
break
}
}
}
export default i18n
import React from 'react'
import i18n from '../locales/i18n'
function HomeScreen({ navigation }) {
return (
{i18n.t('home.welcome')}
{i18n.t('home.content')}
)
}
export default HomeView
{
"home": {
"welcome": "Bienvenue",
"content": "Du contenu ici"
}
}