DEV Community

Marcin Wosinek
Marcin Wosinek

Posted on • Originally published at how-to.dev

How to use basic translation features in i18next

I'll show you how to use basic translation features in i18next:

  • nested keys
  • substitution

Starting point

We start with the code in the previous step. It's already set up for the node & browser use.

Code

The complete code to be placed in in src/index.js:

import i18next from "i18next";

const en = {
  translation: {
    hello_world: "hello world",
    nested: {
      key: "This key is was read from nested object",
    },
    great: "Hello {{name}}",
  },
};

i18next
  .init({
    lng: "en", // if you're using a language detector, do not define the lng option
    resources: {
      en,
    },
  })
  .then((t) => {
    console.log(t("hello_world"));
    console.log(t("nested.key"));
    console.log(t("great", { name: "Marcin" }));
  });
Enter fullscreen mode Exit fullscreen mode

Nested keys

It allows us to organize our keys in some logical structure. For example, we could have something like:

{
  "dialogBox": {
    "close": "Close"
    "ok": "OK"
  },
  "error": {
     "notEnoughSpace": "Not enough space"
  }
}
Enter fullscreen mode Exit fullscreen mode

Variable interpolation

The basic feature of any i18n library. It allows us to put placeholders in the translation & set the value in the runtime.

Working application

The code in action:

$ node src/index.js 
hello world
This key is was read from nested object
Hello Marcin
Enter fullscreen mode Exit fullscreen mode

Links

Summary

In this article, we have seen how to use basic translation features from i18next.

Top comments (0)