How To Implement React Native Multi Language Support

Providing multi-language support in any app will be more helpful in targeting users who do not know how to communicate and use the English language. So we can implement react native multi language support in our app, which can be more productive. Many users want the app in their preferred language; otherwise, they will drop out of the app.

How Do You Implement It?

1. Create a new react native project using the below command:

npx react-native init MultiLanguageSupportDemo

2. Install node modules and pods and run the project one time using Xcode.

3. You can implement basic routing with bottom tab navigation using react-navigation.

4. You need to install react-native-localize, react-native-restart and react-native-event-listeners packages by hitting the below command.

yarn add  react-native-restart  react-native-localize

cd ios && pod install

5. The Project Structure will look like the given below.

How To Implement Multi Language Support In React Native

6. Now you have to make some files for localization in the project->src->localization folder.

7. The First file we have to create is languagekeys.js because, in that, we will add all keys in the string to maintain a multi-language feature. So paste the content below into it.

const languagekeys = {

    helloeveryone: "helloeveryone",

    demomultisupport: "demomultisupport",

    summary: "summary",

    changeLanguage: "changelanguage",

    submit: "submit",

    youcanchange: "youcanchange"

}

export default languagekeys;

8. Now we will create en.js because, in that, we will add all text containing the English language translation. So paste the content below into it.

import languagekeys from "./languagekeys";

const en = {

    [languagekeys.helloeveryone]: 'Hello Everyone',

    [languagekeys.demomultisupport]: "This is the Demo of multi language support in react-native",

    [languagekeys.summary]: "Summary",

    [languagekeys.changeLanguage]: "Change Language",

    [languagekeys.submit]: "Submit",

    [languagekeys.youcanchange]: "You can change your language from here.",

}

export default en;

9. Now, we will create gj.js because we will add all text containing the translation for the Gujarati language. So paste the content below into it.

  import languagekeys from "./languagekeys";

const gj = {

    [languagekeys.helloeveryone]: 'બધાને હેલો',

    [languagekeys.demomultisupport]: "આ રિએક્ટ-નેટિવમાં મલ્ટી લેંગ્વેજ સપોર્ટનો ડેમો છે",

    [languagekeys.summary]: "સારાંશ",

    [languagekeys.changeLanguage]: "ભાષા બદલો",

    [languagekeys.submit]: "સબમિટ કરો",

    [languagekeys.youcanchange]: "તમે અહીંથી તમારી ભાષા બદલી શકો છો.",

}

export default gj;

10. Now we will create hin.js because, in that, we will add all text which contains the translation for the Hindi language. So paste the content below into it.

import languagekeys from "./languagekeys";

const hin = {

    [languagekeys.helloeveryone]: 'सभी को नमस्कार',

    [languagekeys.demomultisupport]: "यह प्रतिक्रिया-मूल में बहु भाषा समर्थन का डेमो है",

    [languagekeys.summary]: "सारांश",

    [languagekeys.changeLanguage]: "भाषा बदलो",

    [languagekeys.submit]: "प्रस्तुत",

    [languagekeys.youcanchange]: "आप यहां से अपनी भाषा बदल सकते हैं।",

}

export default hin;

11. Now, we must create a simple class for managing functionality for multi-language support. So we will make a LanguageUtils.js file, and we have to import the required files as given below.

import * as RNLocalize from "react-native-localize";

import StorageService from "../utils/StorageService";

import en from "./en";

import gj from "./gj";

import hin from "./hin";

12. We will define the class as a file name and have to define obj, which contains how many languages we need to add to the application.

export default class LanguageUtils {

    static languages = {

        english: "english",

        gujarati: "gujarati",

        hindi: "hindi",

    }

}

13. Now, we have to add one static constant, which we will use to change language globally.

static changeLanguageGlobal = "CHANGE_LANGUAGE_GLOBAL"

14. Next, we need to add an array of locales that we need in the app.

 static indianLocales = ['en', "gu-IN", "hi-IN"]

15. Now we will add one constant, which gives us the current language, and if not set, then by using one method, we have to set it. So we will use the react-native-localize lib’s one method and pass all locales, giving the best suitable language localization value from a mobile device; then, we can set language to local async storage.

static currentAppLanguage = this.setAppLangaugeFromDeviceLocale(true);

static setAppLangaugeFromDeviceLocale(needToGetLang) {

       let deviceLocale = RNLocalize.findBestAvailableLanguage(this.indianLocales);


        const languageTag = deviceLocale?.languageTag || "en"

        const isGujDetected = this.indianLocales.find((locale) => 'gu-IN' === languageTag);

        const isHinDetected = this.indianLocales.find((locale) => 'hi-IN' === languageTag);

        const language = isGujDetected

            ? this.languages.gujarati

            : isHinDetected

                ? this.languages.hindi

                : this.languages.english;

        if (needToGetLang) {

            return language;

        }

        this.setAppLangauge(language);

    }

static async setAppLangauge(language) {

        this.currentAppLanguage = language;

        await StorageService.saveItem(StorageService.APP_LANGUAGE, language);

    }

16. Now we will add one method, which we call once when our app is mounted. So basically, it does one thing, if the user already chooses the language, it will set it for the whole app; otherwise, it will store language from device suitable locales.

static async setAppLangaugeFromDeviceStorage() {

        const language = await StorageService.getItem(StorageService.APP_LANGUAGE);

        console.log("language", language);

        if (language) {

            this.setAppLangauge(language);

        } else {

            this.setAppLangaugeFromDeviceLocale();

        }

    }

17. Now we will add one method which returns the localization value for a particular selected language and will display it on screens. By default, it returns the English language localization value.

static getLangText(key) {

        if (this.currentAppLanguage === this.languages.gujarati) {

            return gj[key];

        }

        if (this.currentAppLanguage === this.languages.hindi) {

            return hin[key];

        }

        return en[key];

    }


18. So the whole code will look like the one given below.

import * as RNLocalize from "react-native-localize";

import StorageService from "../utils/StorageService";




import en from "./en";

import gj from "./gj";

import hin from "./hin";




// http://www.lingoes.net/en/translator/langcode.htm




/**

 * Language Localization class 

 */

export default class LanguageUtils {

    /**

     * list of all languages which we wan to apply in app

     */

    static languages = {

        english: "english",

        gujarati: "gujarati",

        hindi: "hindi",

    }




    /**

     * @const for change language globally

     */

    static changeLanguageGlobal = "CHANGE_LANGUAGE_GLOBAL"




    /**

     * list of locales for all languages

     */

    static indianLocales = ['en', "gu-IN", "hi-IN"]




    /**

     * @returns current selected language in app.

     */

    static currentAppLanguage = this.setAppLangaugeFromDeviceLocale(true);




    /**

     * @param {*} needToGetLang 

     * set the default language from device locales  

     */

    static setAppLangaugeFromDeviceLocale(needToGetLang) {

        let deviceLocale = RNLocalize.findBestAvailableLanguage(this.indianLocales);




        const languageTag = deviceLocale?.languageTag || "en"




        const isGujDetected = this.indianLocales.find((locale) => 'gu-IN' === languageTag);

        const isHinDetected = this.indianLocales.find((locale) => 'hi-IN' === languageTag);




        const language = isGujDetected

            ? this.languages.gujarati

            : isHinDetected

                ? this.languages.hindi

                : this.languages.english;




        if (needToGetLang) {

            return language;

        }




        this.setAppLangauge(language);

    }




    /**

     * set the language from device local storage 

     * App will select language from local storage and will set it as Default language for app.

     * if language is not found from storage then will select from device locales.

     */

    static async setAppLangaugeFromDeviceStorage() {

        const language = await StorageService.getItem(StorageService.APP_LANGUAGE);

        console.log("language", language);

        if (language) {

            this.setAppLangauge(language);

        } else {

            this.setAppLangaugeFromDeviceLocale();

        }

    }




    /**

     * 

     * @param {*} language 

     * sets the app language in app

     */

    static async setAppLangauge(language) {

        this.currentAppLanguage = language;

        await StorageService.saveItem(StorageService.APP_LANGUAGE, language);

    }




    /**

     * 

     * @param {*} key 

     * @returns the string value of key in selected language

     */

    static getLangText(key) {

        if (this.currentAppLanguage === this.languages.gujarati) {

            return gj[key];

        }

        if (this.currentAppLanguage === this.languages.hindi) {

            return hin[key];

        }




        return en[key];

    }

}

19. Now we will move to the part which shows how to use this class and how we can implement it.

20. As I said earlier, we have to set the language from device storage, and if the user has not chosen a language, then we can select a language from device locales. We have to add this method to our main app routing file.

useEffect(() => {

        LanguageUtils.setAppLangaugeFromDeviceStorage().then(() => {

            setisReady(true)

        }).catch(() => {

            setisReady(true)

        })

    }, [])

21. Now the Home screen looks like the one below. And whenever we want to display text, we need to use LanguageUtils.getLangText() method in that we need to pass languagekeys’s key value like given below.

import React from 'react';

import { Text, View } from 'react-native';

import languagekeys from '../localization/languagekeys';

import LanguageUtils from '../localization/LanguageUtils';
const Home = () => {

    return (

        <View>

            <Text style={{ color: "black" }}>{LanguageUtils.getLangText(languagekeys.helloeveryone)}</Text>

            <Text style={{ color: "black", marginTop: 20 }}>{LanguageUtils.getLangText(languagekeys.demomultisupport)}</Text>

        </View>

    )

}

export default Home;

22. Now, in the Other Settings screen, we will give a list of languages from which the user can select his preferred language. So users select any language by selecting the radio button.

import React, { useEffect, useState } from 'react';

import { Button, FlatList, Text, TouchableOpacity, View } from 'react-native';

import { EventRegister } from 'react-native-event-listeners';

import languagekeys from '../localization/languagekeys';

import LanguageUtils from '../localization/LanguageUtils';




const Setting = () => {




    const [languageList, setList] = useState([

        {

            key: 'english',

            title: "English",

        },

        {

            key: 'gujarati',

            title: "ગુજરાતી",

        },

        {

            key: 'hindi',

            title: "हिन्दी",

        },

    ])




    const [selectedLanguage, setSelectedLanguage] = useState()




    useEffect(() => {

        setSelectedLanguage(LanguageUtils.currentAppLanguage)

    }, [])




    const renderListItem = ({ item, index }) => {

        return (

            <TouchableOpacity style={{

                marginVertical: 7,

                flexDirection: "row",

                justifyContent: "space-between",

                paddingHorizontal: 20

            }}

                onPress={() => setSelectedLanguage(item.key)}

            >

                <Text

                    style={{

                        color: "black",

                        textTransform: "capitalize",

                    }}

                >{item.title

                    }</Text>

                <View style={{ height: 20, width: 20, borderWidth: 2, borderRadius: 50, alignItems: "center", justifyContent: "center" }}>

                    {

                        item.key == selectedLanguage ? <View style={{ height: 10, width: 10, backgroundColor: "black", borderRadius: 40 }} /> : null

                    }

                </View>

            </TouchableOpacity>

        )

    }




    const onClickSubmit = () => {

        EventRegister.emit(LanguageUtils.changeLanguageGlobal, selectedLanguage)

    }




    return (

        <View>

            <Text style={{ color: "black" }}>{LanguageUtils.getLangText(languagekeys.youcanchange)}</Text>




            <FlatList

                data={languageList}

                renderItem={renderListItem}

                contentContainerStyle={{ flexGrow: 1, paddingVertical: 30 }}

            />




            <Button

                title={LanguageUtils.getLangText(languagekeys.submit)}

                onPress={onClickSubmit}

            />

        </View>

    )

}
export default Setting;

23. After that, when the user clicks on the submit button, we will process the change of language globally for the whole application. So we will pass one event using the react-native-event-listeners module. So our main app navigator will receive that event and change language in the entire application. For that, we have to restart our application using the react-native-restart module.

useEffect(() => {

        const listener = EventRegister.addEventListener(LanguageUtils.changeLanguageGlobal, (language) => {

            LanguageUtils.setAppLangauge(language).then(() => {

                RNRestart.Restart();

            }).catch(() => {

                console.log("error");

            })

        })

        return () => {

            EventRegister.removeEventListener(listener)

        }

    }, [])

24. Application screenshots are given below.

How To Implement Multi Language Support In React Native How To Implement Multi Language Support In React Native How To Implement Multi Language Support In React Native How To Implement Multi Language Support In React Native How To Implement Multi Language Support In React Native

Code Link: Link 1

Demo Video Link: Link 2

coma

Conclusion

If you want to implement multi-language support in react native, you need to follow the above steps as we did. Developers can also add other languages, and they need to add files and locales. So by this feature, we can reach out to more people worldwide and expand it more.

Ronak K

React-Native Developer

Ronak is a React-Native developer with more than 4 years of experience in developing mobile applications for Android and iOS. He is dedicated to his work and passion. He worked in different kinds of application industries that have responsive designs. He also has knowledge of how to make an app with expo cli and react-native web and some basic understanding of react.js.

Keep Reading

Keep Reading

Mindbowser is excited to meet healthcare industry leaders and experts from across the globe. Join us from Feb 25th to 28th, 2024, at ViVE 2024 Los Angeles.

Learn More

Let's create something together!