Basic Usage (hook)
Render a text based on the users browser language. If your browsers language is set to de it will render Hallo Welt! and if the browsers language is set to en it will render Hello World!
Create the translations for your application.
// ./i18n/index.jsconst data = {de: {text: "Hallo Welt!",},en: {text: "Hello World!",},};export { data };
Import your data and import the useI18n function from react-i18n-kit and you are ready to go.
import React from "react";import { useI18n } from "react-i18n-kit";import { data } from "./i18n";/*if language is:- en:i18n.text: "Hello World!"- de:i18n.text: "Hallo Welt!"*/const Text = () => {const { i18n } = useI18n(data)return (<div>{i18n.text}</div>);};export { Text };
Take a look at the output.
As you see you get access to a i18n property. To make that hook work properly we have to pass an object with with keys set to a ISO 639-1 code. Then the hook simply passes only the object with the corresponding language to the i18n property.
For example your browser language is set to en-US, i18n will be:
{"text": "Hello World!"}
You can pass everything you want into these objects, but every language object has to contain the same keys (in this example text), which you will use in your enhanced component.