How to use React Native Localize in React Native apps

Published on Jan 1, 2020

5 min read

REACT-NATIVE

Not every app require global customers but if you have plans to have, you would need internationalization in your React Native app. Using react-native-localize your app can detect the operating system or the device language and support the multi-languages.

In this tutorial, let us build a small demo that uses react-native-localize along with a popular internationalization library i18n-js. The app will display some mock locales based on the device's language and region settings.

Table of contents

🔗
  • Requirements
  • Installing react-native-localize
  • Add locales
  • Add i18n Functionality
  • Completing the App component
  • Run the app
  • Conclusion

Requirements

🔗
  • Node.js >= 10.x.x version installed
  • watchman
  • react-native-cli

Do note that I’m going to use an iOS simulator for this tutorial.

Installing react-native-localize

🔗

To get started, open a terminal window and generate a new React Native app. Also, install the following dependencies after navigating inside the app directory.

react-native init rni18nDemo
cd rni18nDemo
yarn add react-native-localize i18n-js lodash.memoize
# for ios only
cd ios/
pod install

If you are using react-native version greater than 0.60.x you won't have to link the library react-native-localize manually. If you are below the specified version, please refer to the module's official documentation here.

This library gives you access to localization constants related to a particular device. These constants are not included in i18n-js library.

The lodash.memoize package is going to be used since i18n-js does not have a concept of caching.

Add locales

🔗

Create two new files en.json and nl.json inside the directory src/translations/. Both of these files are for separate languages: English, and Dutch. Inside these files are JSON objects that have key-value pairs. The key for both files or the languages is going to be the same. The value for each key is going to differ as it contains the actual translation.

Following are the contents of each file:

1// en.json
2{
3 "hello": "Hello!",
4 "Good morning": "Good morning",
5 "Currency": "USD"
6}
7
8// nl.json
9{
10 "hello": "Hallo!",
11 "Good morning": "Goedemorgen",
12 "Currency": "EUR"
13}

Add i18n Functionality

🔗

Open App.js file and import the following statements.

1import React from 'react';
2import * as RNLocalize from 'react-native-localize';
3import i18n from 'i18n-js';
4import memoize from 'lodash.memoize';
5import { SafeAreaView, StyleSheet, Text } from 'react-native';

Next, require the translation files from the directory created in the previous step, using an object translationGetters.

1const translationGetters = {
2 en: () => require('./src/translations/en.json'),
3 nl: () => require('./src/translations/nl.json')
4};

Add the helper function translate that is going to translate the keywords on the language selection.

1const translate = memoize(
2 (key, config) => i18n.t(key, config),
3 (key, config) => (config ? key + JSON.stringify(config) : key)
4);

Next, add another helper method that is going to detect the fallback language when there is no proper translation available for a particular word or phrase.

Also, using RNLocalize.findBestAvailableLanguage() method, you can let the app detect the possible language tag (value for each tag is coming from the language getters object) and if not tag is available, it is going to use the fallback language tag. This method can also be used with some languages to detect their reading direction (such as RTL).

1const setI18nConfig = () => {
2 const fallback = { languageTag: 'en' };
3 const { languageTag } =
4 RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
5 fallback;
6
7 translate.cache.clear();
8
9 i18n.translations = { [languageTag]: translationGetters[languageTag]() };
10 i18n.locale = languageTag;
11};

Completing the App component

🔗

Lastly, let us create the App component. In the App.js file, start by adding a constructor method that is going to be used to set the i18n config helper method.

1class App extends React.Component {
2 constructor(props) {
3 super(props);
4 setI18nConfig();
5 }
6
7 // ...
8}
9
10export default App;

Then, using the lifecycle methods componentDidMount and componentWillUnmount, you are going to add and remove event listeners to listen for any localization change.

1componentDidMount() {
2 RNLocalize.addEventListener('change', this.handleLocalizationChange)
3 }
4
5 componentWillUnmount() {
6 RNLocalize.removeEventListener('change', this.handleLocalizationChange)
7 }
8
9 handleLocalizationChange = () => {
10 setI18nConfig()
11 .then(() => this.forceUpdate())
12 .catch(error => {
13 console.error(error)
14 })
15 }

Here is the rest of the component file with the render method and the styles used in it. Apart from translation locales, react-native-localize provide ready to use helper methods such as getCountry(). This particular method returns a value in the form of a country code based on the device's locale.

1render() {
2 return (
3 <SafeAreaView style={styles.safeArea}>
4 <Text style={styles.value}>{translate('hello')}</Text>
5 <Text style={styles.value}>{translate('Good morning')}</Text>
6 <Text style={styles.value}>Currency: {translate('Currency')}</Text>
7 <Text style={styles.value}>Country: {RNLocalize.getCountry()}</Text>
8 </SafeAreaView>
9 )
10}
11
12// styles
13const styles = StyleSheet.create({
14 safeArea: {
15 backgroundColor: 'white',
16 flex: 1,
17 alignItems: 'center',
18 justifyContent: 'center'
19 },
20 value: {
21 fontSize: 24
22 }
23})

Run the app

🔗

Make sure you build the app before running it on the platform of your choice. Here are the commands you need to run depending on the device.

# ios
react-native run-ios
# android
react-native run-android

When the app's build process is complete, it is going to run the English locales by default.

On changing the locale, the correct result is reflected in the app.

Conclusion

🔗

This completes the tutorial on how to use react-native-localize to add and use language translations in a React Native app.

Here is the complete code for this demo in a Github repo.

Checkout Jonathan Palma's who wrote a small i18n library after being inspired from this post. Check the library here on GitHub.

Originally published at Heartbeat.fritz.ai


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. In this blog, I write about Technical writing, Node.js, React Native and Expo.

Currently, working at Expo. Previously, I've worked as a Developer Advocate, and Senior Content Developer with companies like Draftbit, Vercel and Crowdbotics.


Copyright ©  2019-2022 Aman Mittal · All Rights Reserved.