react-native-localize and i18n-js

Nicolas KOVACS
Jan 30 · 2 min read

Recently react-native-i18n has been deprecated in favor of react-native-localize, here is how you can keep the same logic as before without recode It all over again. It’s the simplest way I could found.


First, install the new dependencies. You should unlink react-native-i18n if you had It and link the new ones.

yarn add react-native-localize

yarn add i18n-js

You should have in your package.json something like this :

"react-native-localize": "^1.0.0",
"i18n-js": "^3.2.1",

If you are using react-native0.60 you don’t need linking anymore and you can pass the next quoted step.

Don’t forget to link new dependencies, for more informations go to github pages linked above.

react-native link


Now create a file where you will initialize i18n-js, let’s call It i18n.js for example in a src/utils folder

import I18n from "i18n-js";
import * as RNLocalize from "react-native-localize";

import en from "./locales/en";
import fr from "./locales/fr";

const locales = RNLocalize.getLocales();

if (Array.isArray(locales)) {
I18n.locale = locales[0].languageTag;
}

I18n.fallbacks = true;
I18n.translations = {
en,
fr
};

export default I18n;

Now in the same folder create a new one named locales for example and create a new file for each locale you want.

Example of en.js

export default {
hello: "Hello"
};

Example of fr.js

export default {
hello: "Bonjour"
};

Don’t forget If you add more locales to import them in i18n.js


Now in any component of your app, import the file created in the first step and initiate I18n as before

import React, { Component } from "react";
import I18n from "./utils/I18n";
class MyComponent extends Component {
render() {
return (
<View>
<Text>{I18n.t("hello")}</Text>
</View>
);
}
}
export default MyComponent;

If you want to get current locale you can use

import * as RNLocalize from "react-native-localize";async handleLocales() {
this.locales = RNLocalize.getLocales();
}

getLocale() {
if (this.locales) {
if (Array.isArray(this.locales)) {
return this.locales[0];
}
}
return null;
}

That’s all, I hope It will help you to understand how to achieve It. Any comments or recommandations are welcome

Happy coding ;)

Nicolas KOVACS

Written by

Full stack web developper, Ruby On Rails lover and react-native supporter. I’m working in the great world of IOT.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade