i18next Setup — i18n

i18next Setup i18next adalah framework i18n paling populer di ekosistem JavaScript. Bisa dipakai di browser, Node.js, React, Vue, dan framework lainnya…

i18next Setup

i18next adalah framework i18n paling populer di ekosistem JavaScript. Bisa dipakai di browser, Node.js, React, Vue, dan framework lainnya. Library react-i18next adalah binding React-nya.

Instalasi

npm install i18next react-i18next i18next-browser-languagedetector i18next-http-backend

Konfigurasi Dasar

// i18n.js
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import HttpBackend from "i18next-http-backend";

i18n
  .use(HttpBackend)            // Load translations via HTTP
  .use(LanguageDetector)       // Detect user language
  .use(initReactI18next)       // Bind to React
  .init({
    fallbackLng: "en",
    debug: process.env.NODE_ENV === "development",

    interpolation: {
      escapeValue: false,      // React sudah escape XSS
    },

    backend: {
      loadPath: "/locales/{{lng}}/{{ns}}.json",
    },

    detection: {
      order: ["localStorage", "navigator", "htmlTag"],
      caches: ["localStorage"],
    },
  });

export default i18n;

File Terjemahan

// public/locales/en/translation.json
{
  "nav": {
    "home": "Home",
    "about": "About",
    "contact": "Contact"
  },
  "hero": {
    "title": "Learn Web Development",
    "subtitle": "Free, interactive, and fun"
  }
}

// public/locales/id/translation.json
{
  "nav": {
    "home": "Beranda",
    "about": "Tentang",
    "contact": "Kontak"
  },
  "hero": {
    "title": "Belajar Web Development",
    "subtitle": "Gratis, interaktif, dan menyenangkan"
  }
}

Penggunaan di React

import { useTranslation, Trans } from "react-i18next";

function Header() {
  const { t, i18n } = useTranslation();

  return (
    <nav>
      <a href="/">{t("nav.home")}</a>
      <a href="/about">{t("nav.about")}</a>

      {/* Interpolasi */}
      <p>{t("welcome", { name: "Ahmad" })}</p>

      {/* Trans component untuk HTML di dalam terjemahan */}
      <Trans i18nKey="terms">
        Dengan mendaftar, kamu setuju dengan <a href="/terms">Syarat & Ketentuan</a>.
      </Trans>

      {/* Ganti bahasa */}
      <button onClick={() => i18n.changeLanguage("id")}>ID</button>
      <button onClick={() => i18n.changeLanguage("en")}>EN</button>
    </nav>
  );
}

Namespaces

// Pisahkan terjemahan per fitur
// public/locales/id/common.json — shared strings
// public/locales/id/auth.json   — login/register
// public/locales/id/dashboard.json

const { t } = useTranslation("auth");    // namespace "auth"
t("login.title")  // dari auth.json

const { t: tCommon } = useTranslation("common");
tCommon("save")    // dari common.json

Yang akan kamu pelajari