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.
Top comments (0)