One of the core features of your app is internationalization (aka I18n), right? Internationalization is all about offering your products in such a way that they can be localized for languages and cultures easily.

In react native there is a very nice library to handle it: https://github.com/AlexanderZaytsev/react-native-i18n. With this library, you can define a list of locales your mobile app supports:

Note: Fallback is important for unfinished translations. So if your fallback language is en and you have a key that is not translated (so not defined in another language) it will use the key from the fallback language instead.

Using the module is also pretty familiar if you come from the web:

One of the lovely things to handle this on the JavaScript side (I developed pure Android apps) is that you can update your .js language files and upload them on the fly using CodePush. That way, for any new language, any new key, any typo being fixed, you do not need to do a full app release (YEAH!).

There was some trickery involved though and that is why I am writing this article. I found out that when using this library on Android, if we change the system language, the app will not update to the new locale till I reload the JS bundle. That is not the Android default behavior so… Let’s fix it!

Need help with React Native?

Hire us

Solving the reload Android problem

Let’s see first what happens on iOS when changing the system language and going back to our app:

As you can see, everything works as expected, our app and bundle gets restarted when coming back to it and we see the new language in place. Let’s see how it behaves on Android:

I googled for an existing solution, I followed this post https://medium.com/@maximtoyberman/changing-locale-in-react-native-android-86fe25cde318 but it did not work for me (the part of restarting). Plus you need a couple of more dependencies: react-native-locale-listener and react-native-restart. In fact, we can solve this on the native side with a few lines of code and we won’t need any more dependencies. Actually, we won’t even need to go through the bridge (all will happen in the native side).

We need to add a couple of cases in our AndroidManifest.xml, look for this line and add the two bold cases:

In theory we just need locale but there is a bug in the Android platform where the locale change won’t trigger if we do not add layoutDirectiontoo.

After that, we can go to our MainActivity.java, it should look like:

Unfortunately, inside onConfigurationChanged we cannot access the old locale and that is why I am using the currentLocale variable. But basically, if we change the locale (change the phone language) we will recreate the react context. This is the result:

Just as we wanted! Not sure about you but I am going to use this technique in any app I need to write, I18n is a must!

Happy coding!

No Comments