How to use React Native Localize in React Native apps

Not every app requires us to consider a global customer base. But if you have plans to include support for international users in your app, you’ll need internationalization in your React Native app. Using react-native-localize, your app can detect the operating system or the device language and support multiple languages.

In this tutorial, we’ll 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, go ahead and 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’re using a react-native version greater than 0.60.x, you won’t have to link the library react-native-localize manually. If you’re 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 the i18n-js library.

The lodash.memoize package is going to be used since i18n-js doesn’t include a concept for 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, respectively. 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.

The following are the contents of each file:

// en.json
{
 "hello": "Hello!",
 "Good morning": "Good morning",
 "Currency": "USD"
}

// nl.json
{
 "hello": "Hallo!",
 "Good morning": "Goedemorgen",
 "Currency": "EUR"
}

Add i18n Functionality

Open the App.js file and import the following statements:

import React from 'react'
import * as RNLocalize from 'react-native-localize'
import i18n from 'i18n-js'
import memoize from 'lodash.memoize'
import { SafeAreaView, StyleSheet, Text } from 'react-native'

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

const translationGetters = {
  en: () => require('./src/translations/en.json'),
  nl: () => require('./src/translations/nl.json')
}

Add the helper function translate, which is going to translate the keywords from the language files.

const translate = memoize(
  (key, config) => i18n.t(key, config),
  (key, config) => (config ? key + JSON.stringify(config) : key)
)

Next, we’ll add another helper method to detect the fallback language when there’s no proper translation available for a particular word or phrase.

Additionally, using the RNLocalize.findBestAvailableLanguage() method, we can enable our app to detect the possible language tag (the value for each tag is coming from the language getters object), and if no tag is available, it will use the fallback language tag. This method can also be used with some languages to detect their reading direction (such as RTL).

const setI18nConfig = () => {
  const fallback = { languageTag: 'en' }
  const { languageTag } =
    RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
    fallback

  translate.cache.clear()

  i18n.translations = { [languageTag]: translationGetters[languageTag]() }
  i18n.locale = languageTag
}

Completing the App component

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

class App extends React.Component {
  constructor(props) {
    super(props)
    setI18nConfig()
  }

  // ...
}

export default App

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

componentDidMount() {
 RNLocalize.addEventListener('change', this.handleLocalizationChange)
 }

 componentWillUnmount() {
 RNLocalize.removeEventListener('change', this.handleLocalizationChange)
 }

 handleLocalizationChange = () => {
 setI18nConfig()
 .then(() => this.forceUpdate())
 .catch(error => {
 console.error(error)
 })
 }

Here’s the rest of the component file with the render method and the styles used in it. Apart from translation locales, react-native-localize provides 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.

render() {
 return (
 <SafeAreaView style={styles.safeArea}>
 <Text style={styles.value}>{translate('hello')}</Text>
 <Text style={styles.value}>{translate('Good morning')}</Text>
 <Text style={styles.value}>Currency: {translate('Currency')}</Text>
 <Text style={styles.value}>Country: {RNLocalize.getCountry()}</Text>
 </SafeAreaView>
 )
}

// styles
const styles = StyleSheet.create({
 safeArea: {
 backgroundColor: 'white',
 flex: 1,
 alignItems: 'center',
 justifyContent: 'center'
 },
 value: {
 fontSize: 24
 }
})

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 will run the English locales by default.

Upon changing the locale, the correct result is reflected in the app:

Conclusion

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

The complete code for this demo in available in this GitHub repo.

If you’d like to receive more React Native tutorials in your inbox, you can sign up for my newsletter here.

Fritz

Our team has been at the forefront of Artificial Intelligence and Machine Learning research for more than 15 years and we're using our collective intelligence to help others learn, understand and grow using these new technologies in ethical and sustainable ways.

Comments 0 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

wix banner square