Example of Localization in React Native Multi Language App

React Native Localization

Here is an Example of Localization in React Native Multi-Language App. Localization is the process of making something local in character or restricting it to a particular place. In the case of application development, it is related to the development of the application according to the local language.

For the localization, we are going to use LocalizedStrings component from react-native-localization library.

How to Use LocalizedStrings Component?

Here is the code snippet of LocalizedStrings we have used in this Example.

const strings = new LocalizedStrings({
  hi: {
    first:"क्या हाल है ?",
    second:"मैं ठीक हूँ ?",
  },
  "ma":{
    first:"तू कसा आहेस ?",
    second:"मी ठीक आहे ?",
  },
  "en":{
    first:"How are You ?",
    second:"I am fine ",
  },
"fr":{
  first:"comment allez vous",
  second:"je vais bien",
}
});

In this example below, we will make a home screen to select the language and will show the text content on the next screen accordingly from a common string repository where we have defined the same text for each language code.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependencies

To install the dependencies open the terminal and jump into your project

cd ProjectName

1. Install react-native-localization dependency to import LocalizedStrings

npm install react-native-localization --save

2. Install following dependencies for react-navigation

npm install @react-navigation/native --save
npm install @react-navigation/stack --save
npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view --save

These commands will copy all the dependencies into your node_module directory.

CocoaPods Installation

Please use the following command to install CocoaPods

cd ios && pod install && cd ..

Project Structure

We are using the following project structure. Please make the following project structure.

Code to Make a Multi-Language App

If you are done with the project structure then please replace the following code

App.js

// Example of Localization in React Native Multi Language App
// https://aboutreact.com/localization-in-react-native/

import 'react-native-gesture-handler';

import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';

import LanguageSelectionScreen from './pages/LanguageSelectionScreen';
import ContentScreen from './pages/ContentScreen';

const Stack = createStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="LanguageSelectionScreen">
        <Stack.Screen
          name="LanguageSelectionScreen"
          component={LanguageSelectionScreen}
          options={{headerShown: false}}
        />
        <Stack.Screen
          name="ContentScreen"
          component={ContentScreen}
          options={{
            title: 'Content Screen', //Set Header Title
            headerStyle: {
              backgroundColor: '#f4511e', //Set Header color
            },
            headerTintColor: '#fff', //Set Header text color
            headerTitleStyle: {
              fontWeight: 'bold', //Set Header text style
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;

LanguageSelectionScreen.js

// Example of Localization in React Native Multi Language App
// https://aboutreact.com/localization-in-react-native/

import React, {useEffect} from 'react';
import {
  SafeAreaView,
  View,
  Text,
  ScrollView,
  Image,
  StyleSheet,
} from 'react-native';
import StringsOfLanguages from './StringsOfLanguages';

const LanguageSelectionScreen = ({navigation}) => {
  const lang = [
    {shortform: 'hi', longform: 'Hindi'},
    {shortform: 'ma', longform: 'Marathi'},
    {shortform: 'en', longform: 'English'},
    {shortform: 'fr', longform: 'French'},
  ];

  const settext = (value) => {
    StringsOfLanguages.setLanguage(value);
    navigation.navigate('ContentScreen', {selectedLanguage: value});
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <View style={styles.container}>
        <Text style={styles.headingStyle}>
          Please Select Preferred Language
        </Text>
        <Image
          source={{
            uri:
              'https://raw.githubusercontent.com/AboutReact/sampleresource/master/language.png',
          }}
          style={styles.imageStyle}
        />
        <ScrollView style={{marginTop: 30, width: '80%'}}>
          {lang.map((item, key) => (
            <View style={styles.elementContainer} key={key}>
              <Text
                onPress={() => settext(item.shortform)}
                style={styles.textStyle}>
                {item.longform}
              </Text>
              <View style={styles.saparatorStyle} />
            </View>
          ))}
        </ScrollView>
        <Text
          style={{
            fontSize: 18,
            textAlign: 'center',
            color: 'grey',
          }}>
          Example of Localization in React Native 
         (Multi Language App)
        </Text>
        <Text
          style={{
            fontSize: 16,
            textAlign: 'center',
            color: 'grey',
          }}>
          www.aboutreact.com
        </Text>
      </View>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 10,
  },
  headingStyle: {
    color: '#191919',
    fontSize: 25,
    textAlign: 'center',
  },
  imageStyle: {
    width: 64,
    height: 64,
    marginTop: 30,
  },
  elementContainer: {
    width: '100%',
    marginTop: 30,
    alignItems: 'center',
  },
  textStyle: {
    color: '#191919',
    fontSize: 25,
  },
  saparatorStyle: {
    height: 0.5,
    width: '60%',
    backgroundColor: '#C2C2C2',
    marginTop: 10,
  },
});

export default LanguageSelectionScreen;

ContentScreen.js

// Example of Localization in React Native Multi Language App
// https://aboutreact.com/localization-in-react-native/

import React, {useEffect} from 'react';
import {SafeAreaView, View, Text, StyleSheet} from 'react-native';
import StringsOfLanguages from './StringsOfLanguages';

const ContentScreen = ({route, navigation}) => {
  useEffect(() => {
    let heading = '';
    if (route.params.selectedLanguage == 'hi') {
      heading = 'Selected Language Hindi';
    } else if (route.params.selectedLanguage == 'ma') {
      heading = 'Selected Language Marathi';
    } else if (route.params.selectedLanguage == 'en') {
      heading = 'Selected Language English';
    } else if (route.params.selectedLanguage == 'fr') {
      heading = 'Selected Language French';
    }
    navigation.setOptions({title: heading});
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.text}>
          {StringsOfLanguages.first}
        </Text>
        <Text style={styles.text}>
          {StringsOfLanguages.second}
        </Text>
      </View>
      <Text
        style={{
          fontSize: 18,
          textAlign: 'center',
          color: 'grey',
        }}>
        Example of Localization in React Native (Multi Language App)
      </Text>
      <Text
        style={{
          fontSize: 16,
          textAlign: 'center',
          color: 'grey',
        }}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    alignItems: 'center',
    padding: 10,
  },
  text: {
    color: '#191919',
    fontSize: 25,
    marginTop: 15,
  },
});

export default ContentScreen;

StringsOfLanguages.js

// Example of Localization in React Native Multi Language App
// https://aboutreact.com/localization-in-react-native/

import LocalizedStrings from 'react-native-localization';

const StringsOfLanguages = new LocalizedStrings({
  hi: {
    first: 'क्या हाल है ?',
    second: 'मैं ठीक हूँ ?',
  },
  ma: {
    first: 'तू कसा आहेस ?',
    second: 'मी ठीक आहे ?',
  },
  en: {
    first: 'How are You ?',
    second: 'I am fine ',
  },
  fr: {
    first: 'comment allez vous',
    second: 'je vais bien',
  },
});

export default StringsOfLanguages;

To Run the React Native App

Open the terminal again and jump into your project using.

cd ProjectName

To run the project on an Android Virtual Device or on real debugging device

react-native run-android

or on the iOS Simulator by running (macOS only)

react-native run-ios

Download Source Code

Output Screenshots

      

This is how you can make a multi-language React Native Application (Localization). If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

8 thoughts on “Example of Localization in React Native Multi Language App”

  1. Hello. How to handle the situation when one of the localization objects does not contain one of the string?
    e.g.
    const strings = new LocalizedStrings({
    hi: {
    first:”क्या हाल है ?”,
    },

    “en”:{
    first:”How are You ?”,
    second:”I am fine “,
    },
    });
    I want to show en second string if it does not exist in hi.

    Thank you.

    Reply
    • {locale !== ‘en’ && locale !== ‘fr’
      ? ‘Translations will fall back to “en” because none available’
      : null}

      Reply
  2. console.error: “Something went wrong initializing the native ReactNativeLocalization module.”Please check your configuration.Did you run ‘react-native link’?”

    This is my error.
    Please help

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.