DEV Community

Luis Beqja
Luis Beqja

Posted on

How to add translation to your website

If you run a website or an application that caters to users from different parts of the world, you would know how important it is to have translations for your content. In this blog post, we will discuss how to add translations on your website using an "internationalization-framework" called i18next.

What is i18next?
i18next is a popular internationalization framework for web applications. It provides a simple and effective way to manage translations and offers a wide range of features to help developers build multilingual applications. The framework is written in JavaScript and can be used with different frontend technologies such as React, Angular, Vue.js and many more.

Install i18next
To start using i18next, you need to install it in your project. You can do this by running the following command in your terminal:
npm install i18next --save

Create Translation Files
After installing i18next, you need to create translation files for each language you want to support. In each translation file, you define key-value pairs that represent the translated strings for your website. For example, if you want to translate an ad, you can create a file named en.json for English and define the ad copy like this:

 {
  "example_copy": "This is an example copy for EN !"
 }
Enter fullscreen mode Exit fullscreen mode

Similarly, you can create translation files for other languages you want to support, such as es.json for Spanish, fr.json for French, and so on.

Initialize i18next
Once you have created translation files, you need to initialize i18next in your code. To do this, you can use the i18next.init() function and pass in configuration options.

import i18next from 'i18next';

const getCurretnUrlLanguage = () => {
 const url = new URL(window.location.href);
 const lang = url.searchParams.get('lang'); // http://localhost:5173/?lang=en
 return lang;
}

i18next.init({
 lng: getCurretnUrlLanguage(),
 fallbackLng: 'en',
 resources: {
   en: {
     translation: await import(`./locales/en.json`)
   },
   es: {
     translation: await import(`./locales/es.json`)
   },
   fr: {
     translation: await import(`./locales/fr.json`)
   }
 }
});

const exampleCopy = i18next.t('example_copy')}

document.querySelector('#app').innerHTML = `
  <div>
    <h1>${exampleCopy}</h1>
  </div>
`
Enter fullscreen mode Exit fullscreen mode

Conclusion
Today we have discussed how to add translations on your website using i18next. With i18next, you can easily manage translations for your website and provide a better user experience for your global audience. If you haven't already, give i18next a try and see how it can help you create multilingual websites and applications.

You can find the example in this repo:
https://github.com/luisbeqja/i18n-translation

i18next site: https://www.i18next.com/

Top comments (0)