Multi-Language support in React Native

09 Sep, 2021
Multi-Language support in React Native: Internationalization of React Native app helps us to target those users who either don’t speak English or are more comfortable using the app in their local language. We can give options to the users to choose from multiple languages that we will offer in our app.
For this kind of situation, we need to implement Multi-Language support in our app. This is where i18next and react-i18next come in handy. This library makes it easier to manage Translations and provides a lot of useful functions.
Approach: 
Creating a fresh React Native Project and installing i18next and react-i18next dependencies.
Creating a JSON file for each language.
Configuring i18next in i18n.js .
Initializing i18next by importing it in App.js.
Importing language functions in App.js and changing the language.
 
Now let’s start with the implementation.
Step 1: Create a fresh React Native Project by running the command
npx react-native init languageDemo
Step 2: Now go into your project folder i.e. language demo.
cd languageDemo
Step 3: Install  i18next and react-i18next Libraries.
npm install i18next --save
npm i react-i18next
Project Structure: It will look like the following.
Step 4Project Structure
Step 4: Creating JSON files. The JSON file contains the translation for each text in our app that we want to show. The file is in JSON format, so every text has a key.
The key is unique for each different text but common for the same text in different languages.
 
1. en.json: contains translations for English.
{
    "translation": {
      "hello":"Hello",
      "this line is translated":"This line is translated"
    }
  }
2. hi.json: Contains translations for Hindi.
{
    "translation": {
      "hello":"नमस्ते",
      "this line is translated":"यह पंक्ति अनुवादित है"
    }
  }
Step 5: Configuring i18next (i18n.js). We will import i18n from ‘i18next’ and initReactI18next from ‘react-i18next’. 
Then we will import our JSON files(en.json and hi.json).
In i18n.use(initReactI18next) we pass the i18n instance to react-i18next which will make it available for all the components via the context api.
The init() function takes an object of {lng , fallbacklng, resources} as parameter.
lng - default language
fallbackLng - Fallback language in case key is not found for any translation.
resources - JSON file for various languages.
Filename: i18n.js
Javascript
import i18n from 'i18next';import {initReactI18next} from 'react-i18next';import en from './en.json';import hi from './hi.json';  i18n.use(initReactI18next).init({  lng: 'en',  fallbackLng: 'en',  resources: {    en: en,    hi: hi,  },  interpolation: {    escapeValue: false // react already safes from xss  }});  export default i18n;
Step 6: We will now import the i18n.js in our App.js file which will initialize i18next. We will then import useTranslation Hook from react-i18next which gives us t and i18n.
t - function which accepts key as parameter and returns the 
    appropriate text based on current language selected.
i18n - object containing function like changeLanguage  
    and other useful values.
In our screen we have two buttons for changing language. There is a Text which will be changed according to the current set language when we press one of the two buttons. To change the language we will use  changeLanguage function which accepts language resource name as parameter and a callback function to execute after the language change is done.
We can check current language by doing console.log(i18n.language)
App.js
import React,{useState} from 'react';import './i18n/i18n';import {View, Text,Pressable} from 'react-native';import {useTranslation} from 'react-i18next';  const App = () => {      const {t, i18n} = useTranslation();    const [currentLanguage,setLanguage] =useState('en');    const changeLanguage = value => {    i18n      .changeLanguage(value)      .then(() => setLanguage(value))      .catch(err => console.log(err));  };    return (   <View        style={{          flex: 1,          backgroundColor: 'white',          alignItems: 'center',          justifyContent: 'space-evenly',        }}>        <Text style={{fontWeight: 'bold', fontSize: 25, color: '#33A850'}}>          {t('hello')}{' '}        </Text>        <Text style={{fontWeight: 'bold', fontSize: 25, color: '#33A850'}}>          {t('this line is translated')}        </Text>        <Pressable          onPress={() => changeLanguage('en')}          style={{            backgroundColor:              currentLanguage === 'en' ? '#33A850' : '#d3d3d3',            padding: 20,          }}>          <Text>Select English</Text>        </Pressable>        <Pressable          onPress={() => changeLanguage('hi')}          style={{            backgroundColor:              currentLanguage === 'hi' ? '#33A850' : '#d3d3d3',            padding: 20,          }}>          <Text>हिंदी का चयन करें</Text>        </Pressable>      </View>  );};  export default App;
Step to run the application: Start the application using the following command : 
npx react-native run-android
Output:
Output
Reference: https://react.i18next.com/guides/quick-start 
Blogathon-2021
React-Native
Blogathon
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
Python program to convert XML to Dictionary
Modes of DMA Transfer
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Hide or show elements in HTML using display property