Easy and efficient Multi-Language in react/react-native apps using Context API.

Hello, This article covers how to use react’s context API for multi-lingual support. You might have seen a lot of articles already, Trust me, this is different :)

The approach I will show you is different than most people use. It is mostly personal preference, and I usually see people try to over-engineer stuff and try to mess up things.

So let’s begin

I will be coding in React-Native, but this is applicable to both. and will be writing some bullet points for React Js people :), So follow along.

For React-native let’s start with an empty expo project.

This is what we are going to build. I know it doesn’t feel much. But trust me. It would be great.

expo init

Start with empty expo project.

We wont be using any external libs for this, Its gonna be pure react.

let’s create our folder structure.

Now, let’s create our translations.js file, I tend to make translations as per screen. It helps in bigger projects, and keep the common translations in common key. In the Image bellow, We can see we have translations for home screen and translations for common texts, like okay etc etc.

Now, our translation file is done, kind off

Let’s begin to create our language context.

Create LanguageContext.js inside your languages folder as shown in the folder structure

So we created Language Provider with initial state/ language of english. and a method for changing the language. So for so good.

Here we are export two things.

1: LanguageContext (Named export)

2: LanguageProvider (Our custom Provider)

Here is a demonstration of our Language provider and language consumer. We are just wrapping our whole app in our provider and where ever we need to access our context data. We use Consumer.

Now let’s create our card.

So far it was almost same as other posts/tutorials show you. Now lets try something else..!!

Confused? If I were you, I would be too. So basically inside our dummy card component we created a custom Text component. and somehow we tell that component to render the the string which is inside translation.js,

let’s say translation.english.homeScreen.hello and it magically knows what to do? and you know the best part? If we would have something like translation.english.homeScreen.button.text It would still work.

I know, it’s weird, So let’s see where the real magic happened. our Text Component.

Not too complicated right? I just used eval from javascript to covert the string into code. no magic, just pure js. It also has a fall back, incase your translations doesn’t exists. It will just use your string.

I find this approach very easy to implement, Now we won’t be needing our Language consumer anywhere else, We can just create our custom text and even give it styles and other props from outside.

Hope this article helps you well for your next multi-lingual project in React :)

You can find the full source code here: