React Native Multi-Language Support
To create a React Native app with multi-language support, you can use the popular react-i18next
library, which is an internationalization-framework for React and React Native applications. This library helps you manage translations and language changes seamlessly. Here's a step-by-step guide on how to implement multi-language support in your React Native app:
Install the required packages:
First, you need to install react-i18next
, i18next
, and i18next-react-native-language-detector
packages. Run the following command:
npm install react-i18next i18next i18next-react-native-language-detector
Create translation files:
Create a folder named translations
in your project's root directory. Inside the folder, create separate JSON files for each language you want to support. For example, create en.json
for English and es.json
for Spanish:
en.json
{
"welcome": "Welcome to our app!",
"hello": "Hello, {{name}}!"
}
es.json
{
"welcome": "¡Bienvenido a nuestra aplicación!",
"hello": "¡Hola, {{name}}!"
}
Configure i18n:
Create a new file named i18n.js
in your project's root directory and configure it as follows:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import RNLanguageDetector from 'i18next-react-native-language-detector';
import en from './translations/en';
import es from './translations/es';i18n
.use(RNLanguageDetector)
.use(initReactI18next)
.init({
resources: {
en: {
translation: en,
},
es: {
translation: es,
},
},
fallbackLng: 'en',
interpolation: {
escapeValue: false,
},
});export default i18n;
Import and initialize i18n in your app:
Import and initialize i18n.js
in your app's entry point, usually index.js
or App.js
. Add the following line at the beginning of the file:
import './i18n';
Use translations in your components:
Now you can use the useTranslation
hook from react-i18next
to access and render translations in your components. Here's an example:
import React from 'react';
import { SafeAreaView, Text, TouchableOpacity } from 'react-native';
import { useTranslation } from 'react-i18next';
const App = () => {
const { t, i18n } = useTranslation(); const changeLanguage = (language) => {
i18n.changeLanguage(language);
}; return (
<SafeAreaView>
<Text>{t('welcome')}</Text>
<Text>{t('hello', { name: 'John' })}</Text> <TouchableOpacity onPress={() => changeLanguage('en')}>
<Text>English</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => changeLanguage('es')}>
<Text>Español</Text>
</TouchableOpacity>
</SafeAreaView>
);
};export default App;
In this example, the t
function is used to access translations, and the changeLanguage
function is used to switch languages at runtime. The t
function supports variable interpolation, as shown in the 'hello' translation.
With these steps, you should have a basic multi-language support setup in your React Native app.