5 Steps To Toggle Between Languages Using Context API

5 Steps To Toggle Between Languages Using Context API

Table of contents

No heading

No headings in the article.

A quick question?

Q. How do you comfort a JavaScript bug? I will answer at last!

download.png

In a diverse country like India, localization or local languages have much more importance than compared elsewhere. Today, web apps have seen exponential growth by just adding different languages. Let us take the example of Facebook. Facebook uses more than 200 languages in its application and is one of the main reasons for its success all around the globe.

When you are working in an MNC or Startup, you generally do not have to worry much as a developer to translate your web app into other languages. A team or service is dedicated to it. But, when it comes to your personal projects, it is advised to write your own localization method. This will have two benefits :

A. It will help you learn concepts and make you aware of how things work behind the scenes.

B. You will have an edge when you are sitting for interviews and applying for jobs.

Let's see now how you can achieve this feat using context API in react by building a simple Product Checkout Page.

Before we start, let's quickly revise useContext hook or Context API in react.

images.png

Yes, it does matter. You must be aware of props, suppose there is a value that you need to use in more than 4 or say 5 components. What would be the traditional way, your answer is right, it's props. But just imagine how terrifying it would be. Yes, you need to keep Drilling. This is what is called prop drilling.

The problem with Prop Drilling is that whenever data from the Parent component will be needed, it would have to come from each level, Regardless of the fact that it is not needed there and simply needed at last.

And, thus a hero is born, Context API.

WhatsApp Image 2022-05-10 at 9.18.52 PM.jpeg

Context API is a key to our happiness, it quenches our thirst for prop drilling. You may think it is very normal, but once you start applying context, you realize that it is one of the most powerful tools.

6fn53z.jpg

Now let's see the code snippet on how to apply localization in our project.

Step 1: I have created a sample snippet of react which has a readymade checkout page with components styled. You can learn and try it out here.

Step 2: The most important step. Let us create a separate useContext component. This involves creating the context, using the context, and consuming the context.

Find the snippet below :

import { useContext, createContext, useState } from "react";

const LanguageProvider = ({ children }) => {
  const [language, setLanguage] = useState("english");
  return (
    <languageContext.Provider value={{ language, setLanguage }}>
      {children}
    </languageContext.Provider>
  );
};
const useLanguage = () => useContext(languageContext);
const languageContext = createContext();
export { useLanguage, LanguageProvider };

Here we first created the context, passed it via a custom hook, and then provided/consumed it. Further, as you can see the keyword value, it's the same value through which we pass the variables we need in our components.

Key thing to note here is that we have initialized the language state to 'english'.

Step 3: We would now translate all the words/sentences we are using in our web app, in this case, checkout page.

Note: It depends on you what you use to translate, either solely you knowledge or use google translator.

In our case of checkout page, here is the object which has two child objects namely english and hindi, you can add more as per your choice. We have kept the key as same the sentence we need to change, the value is changing as per the translation.

const library = {
  english: {
    "My Shopping Cart": "My Shopping Cart",
    "Deliver to: Admin user, 43789": "Deliver to: Admin user, 43789",
    "Change Address": "Change Address",
    "Loki Laptop Sticker": "Loki Laptop Sticker",
    "Easy to use sticker without harming mettalic.":
    "Easy to use sticker without harming mettalic.",
    "₹99 ₹199 ( 48% off )": "₹99 ₹199 ( 48% off )",
    "Move to wishlist": "Move to wishlist",
    "Coupons": "Coupons",
    "Apply Coupons": "Apply Coupons",
    "PRICE DETAILS : (1 items)": "PRICE DETAILS : (1 items)",
    "Total MRP:": "Total MRP:",
    "Discount on MRP :": "Discount on MRP :",
    "Delivery Charges :": "Delivery Charges :",
    "Total Amount :": "Total Amount :",
    "Place Order": "Place Order",
    "FREE": "FREE"
  },
  hindi: {
    "My Shopping Cart": "मेरी खरीदारी की टोकरी",
    "Deliver to: Admin user, 43789":
    "इसे वितरित करें: व्यवस्थापक उपयोगकर्ता, 43789",
    "Change Address": "पता बदल जाना",
    "Loki Laptop Sticker": "लोकी लैपटॉप स्टिकर",
    "Easy to use sticker without harming mettalic.":
    "धातुई को नुकसान पहुंचाए बिना स्टिकर का उपयोग करना आसान है।",
    "₹99 ₹199 ( 48% off )": "₹99 ₹199 (48% छूट)",
    "Move to wishlist": "इच्छा सूची की ओर बढें",
    "Coupons": "कूपन",
    "Apply Coupons": "कूपन लागू करें",
    "PRICE DETAILS : (1 items)": "मूल्य विवरण: (1 आइटम)",
    "Total MRP:": "कुल एमआरपी:",
    "Discount on MRP :": "एमआरपी पर छूट:",
    "Delivery Charges": "वितरण शुल्क",
    "Total Amount :": "कुल राशि :",
    "Place Order": "आदेश देना",
    "FREE": "नि: शुल्क"
  }
};
export { library };

istockphoto-928810368-612x612.jpg

Step 4: Now, we will grab the key value pair and change the values. For Example, see the code snippet below :

 <h2 className="text-align-center top-margin-7rem">
        <i className="fa-solid fa-cart-shopping red"></i>  {`${library[language]["My Shopping Cart"]}`}
      </h2>

You can see here, we go select library[language] that is the value and then we supply it the key we defined in the object.

Step 5 : Drink some water, have a chocolate milkshake and realx.

download (2).jpg

And, Voila! We are done, this is the step you need to repeat everywhere you have used plain english.

fc4a0774f810c1168531061a219e68c5.jpg

Let's summarize what we learned today :

  • First, we create a language context.
  • We create an Object to translate the text to other languages as per our need.
  • Use the dynamic value, where text needs to be changed as per the need.
  • At last, sip some water and pat your back as you have done a good job.

As I promised, Here is the full working solution of the problem we discussed.

Answer to the top most question - it is simple, you console it. Works with both JS and your girlfriend ( if you have one )

I hope you liked the concept and approach we discussed here. Give a thumbs up, if you enjoyed it.

Follow me on Twitter