Translate Website to Any Language - i18next Library

Translate Website to Any Language - i18next Library

Translating React Website using i18next library

Today, we are going to add a language translation feature to the website. I saw that on Google even on YouTube no video clears all questions and people are struggling. Currently, I am facing an issue that I will tell you in the end. But it's confirmed that after reading this blog you are not going to move to another blog.

Here we are going to use i18next Library and React Framework. Here is an example:

asdf

i18next Library

i18next is a JavaScript library that helps with internationalization (i18n) in web applications. It allows developers to easily manage translations and handle language switching. With i18next, you can make your app accessible to users from different regions, providing them with a localized experience.

Setting Environment

  • ✅ It's obvious to first create react app. Therefore, open the terminal and run:
npx creat-react-app <app-name>
  • ✅ After creating react app, now we are going through all the dependencies that are required to install.
  • ✅ Run the following command in the terminal:

  • Install i18next library using:

npm i i18next
  • Few more to install:
npm i react-i18next i18next-http-backend i18next-browser-languagedetector

Creating Components

As we have done with creating applications and with dependencies. Now we are going to add content to the website. Add a simple paragraph with some heading. Also, We are going to create two components & don't forget to import them to App.js:

  • The first one is for the drop-down menu for selecting languages.

  • And the second one is am creating to explain to you all more about how to add this feature to different pages and components.

Note:- To create components folder is under src folder.

Here is the code added to App.js:

<h1>Why React?</h1>
<p>
 React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.
</p>

Let's create drop-down menu component: To create this component I named the file LangSelector.js under the components folder and added this JSX:

LangSelector.js

import React from 'react'

export default function LangSelector() {
    return (
        <select name="" id="">
            <option key={""}>Languages</option>
            <option key={"en"} value="en">English</option>
            <option key={"hi"} value="hi">Hindi</option>
            <option key={"ru"} value="ru">Russian</option>
        </select>
    )
}

Here languages with code can be added as per the user's need.

Creat a second component and named the file ReactKeys.js and add this JSX:

ReactKeys.js

import React from 'react'

export default function ReactKeys() {

    return (
        <div>
            <h1>ReactJs Keys</h1>
            <p>
                After answering what is ReactJs, let us know what keys are.

                While dealing with components that are rendered dynamically in React, keys are essential. When a key value is set, it helps React identify each component uniquely, even after modifications. Keys assist React in determining which elements have changed, been removed, or been added.

                When creating lists of components in React, it is necessary to use a special attribute called 'key'. React uses keys to track and identify which list items have been modified, removed, or added. In other words, keys are used to uniquely identify components within lists.
            </p>

        </div>
    )
}

Create i18n.js file

This file is very important to create as this will help us to translate. So, create this folder under src the folder. Now add the JSX:

i18n.js

import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

i18next
    .use(Backend)
    .use(LanguageDetector)
    .use(initReactI18next)
    .init({
        fallbackLng: 'en',
        debug: true,
        whitelist: ['en', 'hi', 'ru'], // add language codes that you want. 
        detection: {
            order: ['navigator', 'htmlTag', 'path', 'subdomain'],
            checkWhiteList: true,
        },
    });

export default i18next;

Importing to Index.js

Since we have done with creating the i18n.js file. To use this file we are going to import this into the index.js or main.jsx file.

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import './i18n'

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Passing Drop-Down Menu Value

Now we have to send the value to the App.js form LangSelector.js. To send value we add this script to the Select tag.

LangSelector.js

<select name="" id="" onChange={e => props.setLang(e.target.value)}>
            <option key={""}>Languages</option>
            <option key={"en"} value="en">English</option>
            <option key={"hi"} value="hi">Hindi</option>
            <option key={"ru"} value="ru">Russian</option>
        </select>

Now define a function setLang to store language to local storage so that whenever users visit the website they don't have to select the language again. Also import useEffect and useTranslation.

Here useTranslation is used to select the text to translate. useEffect will help to set the language. In, we fetch language code from local storage and then pass it to i18next.changeLanguage().

App.js

import './App.css';
import ReactKeys from './components/ReactKeys'
import LangSelector from './components/LangSelector'
import { useEffect } from 'react';
import i18next from 'i18next';
import { useTranslation } from 'react-i18next';

function App() {

  const { t } = useTranslation()

  useEffect(() => {
    const lang = localStorage.getItem("language")
    i18next.changeLanguage(lang)
  }, [])

  const setLang = (data) => {
    console.log(data)
    localStorage.setItem('language', data)
    window.location.reload()

  }
  return (
    <>
      <LangSelector setLang={setLang} />
      <h1>{t("Why React?")}</h1>
      <p>
        {t("React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.")}
      </p>
      <ReactKeys />
    </>
  );
}

export default App;

In the same way, we have to do this for the ReactKey.js. In this component, we have to only import useTranslation.

ReactKeys.js

import React from 'react'
import { useTranslation } from 'react-i18next'

export default function ReactKeys() {

    const { t } = useTranslation()

    return (
        <div>
            <h1>{t("ReactJs Keys")}</h1>
            <p>
                {t("After answering what is ReactJs, let us know what keys are.")}

                {t("While dealing with components that are rendered dynamically in React, keys are essential. When a key value is set, it helps React identify each component uniquely, even after modifications. Keys assist React in determining which elements have changed, been removed, or been added.")}

                {t("When creating lists of components in React, it is necessary to use a special attribute called 'key'. React uses keys to track and identify which list items have been modified, removed, or added. In other words, keys are used to uniquely identify components within lists.")}
            </p>

        </div>
    )
}

In this way we can do this for more components. Only have to import useTranlsation and wrap the text into t.

Creating Language Translation File

This is a crucial step here we have to Create the folder locales to the public folder. Under locales create folders of the language code name and under these folders create a language translation file.

Please note that the language translation file must be named translation.json it's compulsory.

Folder structure

folder structure

Adding JSON to translation.json

Here under en folder, translation.json write the text as key which we wrapped in t also as value.

translation.json of en folder content

{
    "Why React?": "Why React?",
    "React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.": "React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.",
    "ReactJs Keys": "ReactJs Keys",
    "After answering what is ReactJs, let us know what keys are.": "After answering what is ReactJs, let us know what keys are.",
    "While dealing with components that are rendered dynamically in React, keys are essential. When a key value is set, it helps React identify each component uniquely, even after modifications. Keys assist React in determining which elements have changed, been removed, or been added.": "While dealing with components that are rendered dynamically in React, keys are essential. When a key value is set, it helps React identify each component uniquely, even after modifications. Keys assist React in determining which elements have changed, been removed, or been added.",
    "When creating lists of components in React, it is necessary to use a special attribute called 'key'. React uses keys to track and identify which list items have been modified, removed, or added. In other words, keys are used to uniquely identify components within lists.": "When creating lists of components in React, it is necessary to use a special attribute called 'key'. React uses keys to track and identify which list items have been modified, removed, or added. In other words, keys are used to uniquely identify components within lists."
}

Now for each language, have to write tranlation.json. The most effective way to do this is to use ChatGPT. Once you did for English, now ask ChatGPT to convert to another language by saying:

Translate the key to Hindi in this JSON file past code here

*Result:

translation.json of hi folder content

{
    "Why React?": "React क्यों?",
    "React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.": "React एक JavaScript आधारित UI विकास पुस्तकालय है। इसे Facebook और एक ओपन स्रोत डेवलपर समुदाय चलाता है। यद्यपि React एक पुस्तकालय है और एक भाषा नहीं है, लेकिन यह वेब विकास में व्यापक रूप से प्रयोग होता है। यह पुस्तकालय मई 2013 में पहली बार आयी थी और अब वेब विकास के लिए सबसे आमतौर पर प्रयोग होने वाली फ्रंटएंड पुस्तकालयों में से एक है।",
    "ReactJs Keys": "ReactJs कुंजी",
    "After answering what is ReactJs, let us know what keys are.": "ReactJs क्या है इसका उत्तर देने के बाद, आइए जानें की कुंजीयें क्या होती हैं।",
    "While dealing with components that are rendered dynamically in React, keys are essential. When a key value is set, it helps React identify each component uniquely, even after modifications. Keys assist React in determining which elements have changed, been removed, or been added.": "React में डाइनेमिक रूप से रेंडर किए जाने वाले कॉम्पोनेंट्स के साथ काम करते समय, कुंजीयें आवश्यक होती हैं। जब कुंजी मान निर्धारित की जाती है, तो यह रिअैक्ट को परिवर्तनों के बाद भी प्रत्येक कॉम्पोनेंट को अद्वितीय रूप से पहचानने में मदतुलचाने में मदद करती है। कुंजीयें रिअैक्ट को बताने में सहायता करती हैं कि कौन से तत्व परिवर्तित हुए हैं, हटाए गए हैं या जोड़े गए हैं।",
    "When creating lists of components in React, it is necessary to use a special attribute called 'key'. React uses keys to track and identify which list items have been modified, removed, or added. In other words, keys are used to uniquely identify components within lists.": "React में कॉम्पोनेंट्स की सूचियों को बनाते समय, एक विशेष गुणांक 'key' का प्रयोग करना आवश्यक होता है। रिअैक्ट कुंजीयें प्रयोग करता है ताकि पता चल सके कि कौन से सूची आइटमों में परिवर्तन हुए हैं, हटाए गए हैं या जोड़े गए हैं। दूसरे शब्दों में कहें तो, कुंजीयें सूचियों के भीतर कॉम्पोनेंट्स को अद्वितीय रूप से पहचानने के लिए प्रयोग होती हैं।"
}

In this way, we do this for all the languages.

Congrats 🎊, We are ready to use this language translation feature.

Result

video

Intuition

What's fascinating about this code is that it knows where to find the translation files without us telling it. By default, it looks for a folder called "locales" and expects the translation file to be named "translation.json". It's like having a built-in understanding of where to find the necessary language translations. Therefore, it must define in the public folder.

Conclusion

i18next Library is easy to use and install. The complex part of this is to write the JSON for each language and I think this becomes the drawback and the site becomes heavier. As it not fetching data or it not using API hence it is faster.

Thank you for reading! 📑 If you enjoyed this content and would like to explore more, make sure to follow me for future updates. You can also connect with me on Twitter 📲 for additional insights and discussions. Stay tuned for more exciting content!"

Did you find this article valuable?

Support Vaibhav Maurya by becoming a sponsor. Any amount is appreciated!