DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Using internationalization with i18n

Using JavaScript, let's create a ...

Code

HTML

<div style="height: 150px">
  <button onclick="i18next.changeLanguage('en')">
    english
  </button>
  <button onclick="i18next.changeLanguage('pt')">
    português
  </button>
  <hr />
  <div id="title"></div>
  <button id="saveBtn"></button>
  <hr />
  <div id="info"></div>
</div>
Enter fullscreen mode Exit fullscreen mode

This code is creating a HTML page with a div element that has a fixed height of 150px. Inside this div element, there are two buttons, one for "english" and the other for "português". These buttons are using the "onclick" event to call the "i18next.changeLanguage" function with either "en" or "pt" as the argument.

JS

async function loadLocales(lang) {
  try {
    const response = await fetch(`locales/${lang}.json`);
    return await response.json();
  } catch (e) {
    console.log('And error occurred: ', e);
  }
}

async function main() {
  // let en = await loadLocales('en');
  // let pt = await loadLocales('pt-BR');
  let en = {
    "translation": {
      "title": "{{what}} in english",
      "button": {
        "save": "save {{count}} change",
        "save_plural": "save {{count}} changes"
      }
    }
  };

  let pt = {
    "translation": {
      "title": "{{what}} em portugues",
      "button": {
        "save": "salvo {{count}} alteração",
        "save_plural": "salvo {{count}} alterações"
      }
    }
  };

  const options = {
    resources: { pt, en },
    lng: 'pt'
  };

  await i18next.init(options);
  updateContent();
}

main();

function updateContent() {
  document.getElementById('title').innerHTML = i18next.t('title', { what: 'i18next' });
  document.getElementById('saveBtn').innerHTML = i18next.t('button.save', { count: Math.floor(Math.random() * 2 + 1) });
  document.getElementById('info').innerHTML = `detected user language: "${i18next.language}"  --> loaded languages: "${i18next.languages.join(', ')}"`;
}

i18next.on('languageChanged', () => {
  updateContent();
});
Enter fullscreen mode Exit fullscreen mode

This code is using the i18next library to handle translations in a web page. The loadLocales function is an async function that takes a language code as an argument and attempts to fetch a JSON file with the corresponding language code from a "locales" directory. If the fetch is successful, it returns the JSON data, otherwise it logs an error to the console.

In the main function, it is loading the english and portuguese JSON data, but it's commented out and hardcoded in the script for demonstration. The main function is then initializing i18next with the loaded resources and the default language 'pt' and then calling the updateContent function.

The updateContent function uses the i18next.t function to translate the text of the elements with the ids "title", "saveBtn" and "info" on the page. The function also sets the innerHTML of the elements with the ids "title", "saveBtn" and "info" with the translations.

Finally, the code is setting an event listener that listens for the "languageChanged" event, and when it occurs, it calls the updateContent function again.

Demo

See below for the complete working project.

💡 NOTE: if you can't see it click here and see the final result

Conclusion

Internationalization (i18n) is a technique used to make a web application or software easily adaptable to different languages and cultures. It allows you to create a single codebase that can be easily translated into different languages without having to maintain multiple versions of the same application.

Using i18n in your projects has several benefits:

  • It allows you to reach a wider audience by making your application accessible to users in different parts of the world, who speak different languages.
  • It makes it easier to maintain your codebase as you only have to update one version of the application instead of multiple versions for different languages.
  • It makes it easier to add new languages to your application in the future.
  • It can improve the user experience for your users by providing them with a version of your application in their preferred language.

Overall, implementing i18n in your projects can greatly benefit both you as a developer and your users, allowing for a more inclusive and user-friendly experience.


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)