i18n

Runnable examples, from a hand-written t to the main i18n libraries. How it works (what goes through t, how setupForm and <Form> combine, what a language switch does): i18n guide.

The translator t

A translator is a function that knows the current language: it takes a key (and params) and returns that key's translation. Here a switch translates labels, descriptions and validation messages, and the whole i18nConfig sits in setupForm.

Your public display name
import { setupForm, defineMapping } from "react-headless-form";
import InputField from "./fields/InputField";

const [Form] = setupForm({
  renderRoot: ({ children, onSubmit }) => (
    <div className="blueform-example">
      <form onSubmit={onSubmit}>{children}</form>
    </div>
  ),
  fieldMapping: defineMapping({ text: InputField }),
  i18nConfig: {
    validationTranslation: {
      required: "validation.required",
      minLength: "validation.minLength",
      pattern: "validation.pattern",
    },
    t: (message, params) => {
      switch (message) {
        case "label.username":
          return "Username";
        case "label.email":
          return "Email";
        case "label.password":
          return "Password";
        case "desc.username":
          return "Your public display name";

        case "validation.required":
          return `${params?.field} is required`;
        case "validation.minLength":
          return `${params?.field} must be at least ${params?.minLength} characters`;
        case "validation.pattern":
          return `${params?.field} format is invalid`;

        default:
          return message;
      }
    },
  },
});

export default function EgI18nValidation() {
  return (
    <Form
      config={{
        username: {
          type: "text",
          label: "label.username",
          description: "desc.username",
          rules: {
            required: true,
            minLength: 3,
          },
        },
        email: {
          type: "text",
          label: "label.email",
          props: { type: "email" },
          rules: {
            required: true,
            pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
          },
        },
        password: {
          type: "text",
          label: "label.password",
          props: { type: "password" },
          rules: {
            required: true,
            minLength: 6,
          },
        },
      }}
      onSubmit={(data) => alert(JSON.stringify(data, null, 2))}
    >
      <button type="submit">Submit</button>
    </Form>
  );
}

i18nConfig in setupForm or on <Form>

  • t does not change while the page runs (one language, or a reload to switch): put the whole i18nConfig in setupForm, as above.
  • t changes when the user switches language: put validationTranslation in setupForm and pass t on <Form>; the two are merged key by key, the Form's keys win (v0.22+). Create t in React, from a library's hook or from your own store with useSyncExternalStore: the form knows the language changed only when it receives a new t.
import { defineMapping, setupForm } from "react-headless-form";
import InputField from "../fields/InputField";

// The fixed part of i18n, once for every form: which keys the validation
// messages use. Each <Form> passes only `t`; the two are merged key by key.
export const [I18nForm] = setupForm({
  renderRoot: ({ children, onSubmit }) => (
    <div className="blueform-example">
      <form onSubmit={onSubmit}>{children}</form>
    </div>
  ),
  fieldMapping: defineMapping({ text: InputField }),
  i18nConfig: {
    validationTranslation: { required: "validation_required", minLength: "validation_min_length" },
  },
});

Override one key (i18nConfig={{ t }}) or all of them on a given form; a key set to undefined drops the setup's value for that form.

When t needs a few lines of wiring (your own store, an adapter around the library's function), put them in a hook of your app, useI18nConfig(), and pass its result to every form: <Form i18nConfig={useI18nConfig()} />. When the library's t fits as is, pass it directly.

The examples below share these messages in two languages:

en.json
vi.json
{
  "$schema": "https://inlang.com/schema/inlang-message-format",
  "username_label": "Username",
  "username_description": "Your public display name",
  "validation_required": "{field} is required",
  "validation_min_length": "{field} must be at least {minLength} characters",
  "placeholder_own": "Translated by your own t",
  "placeholder_i18next": "Translated by i18next",
  "placeholder_react_intl": "Translated by react-intl",
  "placeholder_lingui": "Translated by Lingui",
  "placeholder_paraglide": "Translated by Paraglide JS"
}

Your own translator

A language store of a few lines: getLang / setLang decide where the language lives (localStorage here, a cookie or the URL works the same), useSyncExternalStore re-renders the form when it changes, and t is a lookup in the JSON.

Your public display name
import { useMemo, useSyncExternalStore } from "react";
import en from "./i18n/en.json";
import { I18nForm } from "./i18n/form";
import vi from "./i18n/vi.json";

type Lang = "en" | "vi";
type Params = Record<string, unknown>;

// 1. Where the language lives: get/set are yours (localStorage here; a cookie
//    or the URL works the same). setLang notifies the subscribed components.
const listeners = new Set<() => void>();
const getLang = (): Lang => (localStorage.getItem("demo-lang") === "vi" ? "vi" : "en");
const setLang = (lang: Lang) => {
  localStorage.setItem("demo-lang", lang);
  listeners.forEach((notify) => notify());
};
const subscribe = (notify: () => void) => {
  listeners.add(notify);
  return () => listeners.delete(notify);
};
// re-renders on setLang(); "en" while rendering on the server
const useLang = () => useSyncExternalStore(subscribe, getLang, () => "en" as const);

// 2. A plain function: also usable outside React (services, API errors, toasts)
//    as translate(getLang(), key, params)
const messages: Record<Lang, Record<string, string>> = { en, vi };
const translate = (lang: Lang, key: string, params?: Params) =>
  (messages[lang][key] ?? key).replace(/\{(\w+)\}/g, (_, name) => String(params?.[name] ?? ""));

// 3. One hook for every form: a new `t` per language, the same one in between
function useI18nConfig() {
  const lang = useLang();
  return useMemo(() => ({ t: (key: string, params?: Params) => translate(lang, key, params) }), [lang]);
}

export default function EgI18nOwnStore() {
  const lang = useLang();
  return (
    <I18nForm
      i18nConfig={useI18nConfig()}
      config={{
        username: {
          type: "text",
          label: "username_label",
          description: "username_description",
          props: { placeholder: "placeholder_own" },
          rules: { required: true, minLength: 3 },
        },
      }}
    >
      <button type="button" onClick={() => setLang(lang === "en" ? "vi" : "en")}>
        {lang === "en" ? "Tiếng Việt" : "English"}
      </button>
      <button type="submit">Submit</button>
    </I18nForm>
  );
}
ProsCons (what a library gives you)
No dependency, a few dozen lines you can readPlurals and ICU syntax ({count, plural, …})
Store the language anywhere: localStorage, a cookie, the URLNumber, date and currency formatting per locale
Translate outside React: translate(getLang(), key) in services, API error mapping, a module-level Zod error map, toastsLoading a locale only when it is used
Easy to debugKey extraction, translation tooling, type-checked keys, fallback locales

Good for a small or medium app with a few languages and simple messages. Once you need plurals, formatting or a translation workflow, use a library. Libraries translate outside React too, each in its own way: i18next.t, Lingui's i18n._, Paraglide's m.key() with getLocale(), react-intl's createIntl().

With an i18n library

The same form with each library: t comes from the library's hook, so the form follows the language, and the rest of the config comes from the shared setup. Submit it empty, then switch the language: the label, the placeholder and the error follow, and the value is kept.

i18next
react-intl
Lingui
Paraglide JS

t from useTranslation(). The largest ecosystem (plugins, backends, detection); here {field} is set as the interpolation syntax to share the JSON.

Your public display name
import i18next from "i18next";
import { useMemo } from "react";
import { initReactI18next, useTranslation } from "react-i18next";
import en from "./i18n/en.json";
import { I18nForm } from "./i18n/form";
import vi from "./i18n/vi.json";

// In an app this lives in your i18n bootstrap file
i18next.use(initReactI18next).init({
  lng: "en",
  resources: { en: { translation: en }, vi: { translation: vi } },
  // the messages use {field}; i18next's default is {{field}}
  interpolation: { escapeValue: false, prefix: "{", suffix: "}" },
});

export default function EgI18nI18next() {
  // `translate` changes with the language. Wrapped because without typed
  // resources its return type also allows objects; a new `t` per language.
  const { t: translate, i18n } = useTranslation();
  const t = useMemo(
    () => (key: string, params?: Record<string, unknown>) => String(translate(key, params)),
    [translate],
  );
  return (
    <I18nForm
      i18nConfig={{ t }}
      config={{
        username: {
          type: "text",
          label: "username_label",
          description: "username_description",
          props: { placeholder: "placeholder_i18next" },
          rules: { required: true, minLength: 3 },
        },
      }}
    >
      <button type="button" onClick={() => i18n.changeLanguage(i18n.language === "en" ? "vi" : "en")}>
        {i18n.language === "en" ? "Tiếng Việt" : "English"}
      </button>
      <button type="submit">Submit</button>
    </I18nForm>
  );
}