paint-brush
Localizing Your React-Native App [A How-To Guide]by@kriss
1,549 reads
1,549 reads

Localizing Your React-Native App [A How-To Guide]

by InstamobileJune 22nd, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Localizing Your React-Native App [A How-To Guide] The Code Magic is a guide to localizing your React Native app. Localization means adapting your app’s translations to suite your customers’ specific country or region. Supporting multiple languages (including RTL) is a critical feature for any successful mobile app, since it opens up the user base to a much larger pool of people, and also improves the user experience tremendously. Localizing in React Native could be a little tricky, which is why we are writing this tutorial.

Company Mentioned

Mention Thumbnail
featured image - Localizing Your React-Native App [A How-To Guide]
Instamobile HackerNoon profile picture

Localization means adapting your app’s translations to suite your customers’ specific country or region. Supporting multiple languages (including RTL) is a critical feature for any successful mobile app, since it opens up the user base to a much larger pool of people, and also improves the user experience tremendously.

 Localization in React Native could be a little tricky, which is why we are writing this tutorial. Let’s see how you can localize your React Native apps elegantly.

Installation

expo-localization is an Expo library that is used to fetch information about the locale of the user and localize your app. It provides information about the user’s locale, timezone, region, and currency Code all of which can help you customize the user experience of your app. Let’s install this package by running:

expo install expo-localization

i18n-js works hand in hand with expo-localization to achieve localization in React Native mobile & web apps.

It’s a small library to provide the Rails I18n translations on the JavaScript.
yarn add i18n-js

lodash.memoize is another library we will need to help us cache translations. Let’s install it as well:

yarn add lodash.memoize

Create your translation config files

Let’s assume we want to support 3 languages in our React Native app: French, English and Spanish. Let’s add a configuration json file for each of them, as follows:

fr.json

{
    "welcome": "Bienvenue dans le didacticiel de traduction"
}

en.json

//en.json
{
    "welcome": "Welcome to translation tutorial",
}

es.json

//es.json
{
    "welcome": "Bienvenida al tutorial de traducción",
}

React Native Localization — The Code Magic

Now that we have the config files ready and that we installed the required dependencies, let’s do the actual implementation for localizing our React Native app.

Let’s create a file called IMLocalized.js and add the following code snippet. As you’ve probably guessed, at Instamobile, we are using exactly the same mechanism to localize our React Native apps, which is where we got this code snippet from. Feel free to rename IMLocalized into your own original name, but we’re going with it for this tutorial (the IM prefix stands for Instamobile).

import memoize from 'lodash.memoize'; // Use for caching/memoize for better performance
import i18n from 'i18n-js';
import * as Localization from 'expo-localization';
import { I18nManager } from 'react-native';

export const translationGetters = {
  'es-US': () => require('./es.json'),
  'en-US': () => require('./en.json'),
  'fr-FR': () => require('./fr.json'),
};

export const IMLocalized = memoize(
  (key, config) =>
    i18n.t(key, config).includes('missing') ? key : i18n.t(key, config),
  (key, config) => (config ? key + JSON.stringify(config) : key),
);

export const init = () => {
    
  let localeLanguageTag = Localization.locale;
  let isRTL = Localization.isRTL;

  IMLocalized.cache.clear();
  // update layout direction
  I18nManager.forceRTL(isRTL);
  // set i18n-js config
  i18n.translations = {
    [localeLanguageTag]: translationGetters[localeLanguageTag](),
  };
  i18n.locale = localeLanguageTag;
};


a breakdown on the functions:

init() figures out the user’s locale and configures i18nIMLocalized() accepts keys of string values stored in our config file and fetches their values and lodash.memoize helps to cache the retrieved value (huge performance benefits)translationGetters() fetches the correct config files depending on the user’s localeCreate your views

To test our app, let’s build a simple custom UI, in order to showcase the powerful localization component.

import React from 'react';
import {IMLocalized, init} from './IMLocalized';
import { View, StyleSheet, Text } from 'react-native';

export function WelcomeScreen(params) {
    init();
    return(
        <View style={styles.container} >
            <Text style={styles.welcomeText} >
                {IMLocalized('welcome')}
            </Text>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center"
    },
    welcomeText: {
        fontSize: 16,
    }
})

Notice the use of IMLocalized. Instead of providing a simple “Welcome” string to the Text component, we wrap it in an IMLocalized call. This is the key part of how we achieve React Native Localization for supporting multiple languages, including RTL. The app will magically display the “Welcome” string into the correct language (based on user’s device setting), rather than showing a hardcoded English string.

Running your app should look like this:

English

Change your device’s settings to Spanish, and reopen the app. Notice how the string is now in Spanish:

Spanish

Change the device settings one more time, to French:

French

Conclusion

Localizing your application is very important to reach a wider range of customers from various parts of the world. Localizing your application is not a gruesome process to undertake as we have seen above.

By using our IMLocalized method, you can simply translate all the strings you have in our app, by wrapping them in an IMLocalized call. You can follow a similar pattern in all the other mobile programming languages, such as Swift, Flutter or Kotlin.

Adding support for multiple languages (including RTL) is pretty straightforward once you set up the infrastructure groundwork. Simply wrapping the hardcoded strings into a translation method is enough.