Easy Way to translate your REACT-NATIVE app

Hey guys, today I Wanna show you a simple way to translate your app.

So before start I like to warn if you want something more elaborate check it out this repo react-native-i18n.

First of all we need to import NativeModules from ‘react-native’ that provide us a atribute localeIdentifier at I18nManager which in turn has a string like that “en_US”.

import { NativeModules } from 'react-native'

After import we will implement a method that find inside object if the given term exist on current localeIdentifier.

function __translate(term) {

//check if localeIdentifier exists
if (NativeModules.I18nManager.localeIdentifier) {

const i18nLocale = NativeModules.I18nManager.localeIdentifier;

console.log(i18nLocale);

//Check if has registered terms in current i18nLocale;
if (TERMS[i18nLocale]){

//Return the registered or empty string to prevent error
return TERMS[i18nLocale][term] || '';

} else {

//Check if has language without a especific region like
//Example en-CA to en
const simplei18nLocale = i18nLocale.split('_')[0];

return TERMS[simplei18nLocale][term] || '';

}
}
}

Note that method will first looking for a language with locale “en_US” or “en_CA” and if there is no locale he just try to check if is at least the language “en” or “es”.

To prevent errors if no terms just return a empty string.

Now we going to write the method that save the terms.

const TERMS = {};
function setTerms(i18nLocale, objectTerms) {
TERMS[i18nLocale] = objectTerms;
}

And then we just use like that

setTerms("en_CA",{
"COMMENT" : "Comment"
})
setTerms("es",{
"COMMENT" : "comentario"
})
setTerms("pt_BR",{
"COMMENT" : "Comentário"
})
...
//IN YOUR REACT COMPONENT
render(){
return (<View><Text>{ __translate("COMMENT") }</Text></View>);
}

Wait, it’s not over yet. So many apps need not only translations but also terms in the plural and singular.

Doing this is very easy, just take a look!!!

function pluralOrSingular(term, value) {
if (value !== 1) {
return __translate(`${term}_PLURAL`)
}
return __translate(`${term}_SINGULAR`)
}
//USAGE
setTerms("en_CA",`{
"COMMENT_SINGULAR" : "Comment",
"COMMENT_PLURAL" : "Comments",
})
pluralOrSingular("COMMENT", 1) // Comment
pluralOrSingular("COMMENT", 2) // Comments

Full code

or https://github.com/tawsbob/examples/blob/master/js/react-native/lang.js

I hope you enjoy this little tip, I’m brazilian and my english is not very well but I´m trying to get better every day, sorry if I made a mistake.

If this post was helpful to you or if you have any suggestions please leave your comment, thanks!!!!!!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.