React Native Localization

React Native localization

Some React Native features may not be clear or easy to implement, but the localization is made really painless.

For localization in React Native we will need to:

  • install the react-native-localization library
  • create an object with localized strings
  • use this object instead of old hardcoded strings.

That’s it. Now let’s go through it.

Install react-native-localization

The simplest way of installing this dependency is by using rnmp (React Native Package Manager).

If you don’t have rnpm istalled, run:

npm install -g rnpm

Now run this command to install react-native-localization inside of your project folder:

rnpm install react-native-localization

Now the library is installed. Let’s proceed to implementation.

Create localized strings

For more comfortable localization support I recommend you to create a separate file with localization strings. Let’s call it local_strings.js. This is its content:

import LocalizedStrings from 'react-native-localization';

export let strings = new LocalizedStrings({
  en:{
    hello_world: "Hello, World!"
  },
  uk: {
    hello_world:"Привіт, Світ",
  }
});

Here you can see an instantiation of a LocalizedStrings object called strings. It contains the only one string called hello_world for English and Ukrainian locales.

Now we can use the hello_world placeholder in the code. And it will be replaced automatically depending on device locale.

Use localized strings

At first, import the strings object into the file with your component (in my case, this file is located in the same directory with local_strings.js):

import { strings } from './local_strings';

Now you can refer strings like that:

<Text>{strings.hello_world}</Text>

NOTE: When you have just installed the library, restart the development server and rebuild the application. Otherwise you will get an error.

Leave a Reply

2 Comments on "React Native Localization"


Guest
Stephane Beaudry
3 months 23 days ago

‘npm install -g rnmp’ should be instead ‘npm install -g rnpm’