Skip to main content

Command Palette

Search for a command to run...

How to use basic translation features in i18next

Published
2 min read
M

I'm JS developer with 13 years of professional experience. I'm always happy to teach my craft.

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" }));
  });

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"
  }
}

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

Links

Summary

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

More from this blog

H

How to dev

164 posts

Articles about programming. JavaScript and general advice for beginners in the industry.