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.
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>
);
}
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:
{
"$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"
}
{
"$schema": "https://inlang.com/schema/inlang-message-format",
"username_label": "Tên người dùng",
"username_description": "Tên hiển thị công khai của bạn",
"validation_required": "{field} là bắt buộc",
"validation_min_length": "{field} phải có ít nhất {minLength} ký tự",
"placeholder_own": "Dịch bởi t tự viết",
"placeholder_i18next": "Dịch bởi i18next",
"placeholder_react_intl": "Dịch bởi react-intl",
"placeholder_lingui": "Dịch bởi Lingui",
"placeholder_paraglide": "Dịch bởi 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.
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>
);
}
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.
t from useTranslation(). The largest ecosystem (plugins, backends, detection); here {field} is set as the interpolation syntax to share the JSON.
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>
);
}
intl.formatMessage({ id: key }, params) from useIntl(). ICU messages, formatting through the browser's Intl.
import { useMemo, useState } from "react";
import { IntlProvider, useIntl } from "react-intl";
import en from "./i18n/en.json";
import { I18nForm } from "./i18n/form";
import vi from "./i18n/vi.json";
const messages = { en, vi };
type Locale = keyof typeof messages;
function UsernameForm({ onToggle }: { onToggle: () => void }) {
// `intl` changes with the locale: a new `t` for each one (ICU messages: {field})
const intl = useIntl();
const t = useMemo(
() => (key: string, params?: Record<string, unknown>) =>
intl.formatMessage({ id: key }, params as Record<string, string>),
[intl],
);
return (
<I18nForm
i18nConfig={{ t }}
config={{
username: {
type: "text",
label: "username_label",
description: "username_description",
props: { placeholder: "placeholder_react_intl" },
rules: { required: true, minLength: 3 },
},
}}
>
<button type="button" onClick={onToggle}>
{intl.locale === "en" ? "Tiếng Việt" : "English"}
</button>
<button type="submit">Submit</button>
</I18nForm>
);
}
export default function EgI18nReactIntl() {
const [locale, setLocale] = useState<Locale>("en");
return (
<IntlProvider locale={locale} messages={messages[locale]}>
<UsernameForm onToggle={() => setLocale(locale === "en" ? "vi" : "en")} />
</IntlProvider>
);
}
_(key, params) from useLingui(). ICU messages compiled at build time by its CLI, a small runtime.
import { setupI18n } from "@lingui/core";
import { compileMessage } from "@lingui/message-utils/compileMessage";
import { I18nProvider, useLingui } from "@lingui/react";
import en from "./i18n/en.json";
import { I18nForm } from "./i18n/form";
import vi from "./i18n/vi.json";
// In an app the Lingui CLI compiles the catalogs at build time;
// this demo compiles the plain ICU messages at runtime instead.
const i18n = setupI18n();
i18n.setMessagesCompiler(compileMessage);
i18n.load({ en, vi });
i18n.activate("en");
function UsernameForm() {
// `_` changes on i18n.activate(); validationTranslation comes from setupForm
const { i18n, _ } = useLingui();
return (
<I18nForm
i18nConfig={{ t: _ }}
config={{
username: {
type: "text",
label: "username_label",
description: "username_description",
props: { placeholder: "placeholder_lingui" },
rules: { required: true, minLength: 3 },
},
}}
>
<button type="button" onClick={() => i18n.activate(i18n.locale === "en" ? "vi" : "en")}>
{i18n.locale === "en" ? "Tiếng Việt" : "English"}
</button>
<button type="submit">Submit</button>
</I18nForm>
);
}
export default function EgI18nLingui() {
return (
<I18nProvider i18n={i18n}>
<UsernameForm />
</I18nProvider>
);
}
Messages compile to typed, tree-shakable functions (m.username_label()), not string keys: config keys are message names and t looks them up.
import { useMemo, useState } from "react";
import { I18nForm } from "./i18n/form";
// generated by `paraglide-js compile` from ./i18n/{locale}.json
import { m } from "./paraglide/messages.js";
type Locale = "en" | "vi";
type Message = (inputs: Record<string, unknown>, options: { locale: Locale }) => string;
// Paraglide compiles each message to a function: `t` looks it up by name
// (an unknown name comes back as is)
const translator = (locale: Locale) => (key: string, params?: Record<string, unknown>) => {
const message = (m as unknown as Record<string, Message | undefined>)[key];
return message ? message(params ?? {}, { locale }) : key;
};
export default function EgI18nParaglide() {
const [locale, setLocale] = useState<Locale>("en");
const t = useMemo(() => translator(locale), [locale]); // a new `t` per locale
return (
<I18nForm
i18nConfig={{ t }}
config={{
username: {
type: "text",
label: "username_label",
description: "username_description",
props: { placeholder: "placeholder_paraglide" },
rules: { required: true, minLength: 3 },
},
}}
>
<button type="button" onClick={() => setLocale(locale === "en" ? "vi" : "en")}>
{locale === "en" ? "Tiếng Việt" : "English"}
</button>
<button type="submit">Submit</button>
</I18nForm>
);
}