React + react-i18next
Translations and language switching with i18next. This page shows exactly what pickstack adds to a React project for react-i18next: the packages, the new files and the changes to existing ones. Every combination is installed, built, linted and tested in CI.
$ npm create pickstack@latest my-app -- --framework react --modules react-i18next --yesCustomize in the configurator
Packages it adds
| Package | Version | Type |
|---|---|---|
i18next | ^27.2.9 | runtime |
react-i18next | ^18.0.3 | runtime |
New files
import { useTranslation } from "react-i18next";
const languages = [
{ code: "en", label: "English" },
{ code: "es", label: "Español" },
];
export default function LanguageSwitcher() {
const { t, i18n } = useTranslation();
return (
<div>
<p className="text">{t("greeting")}</p>
<div className="row">
{languages.map(({ code, label }) => (
<button
key={code}
type="button"
className="btn"
aria-pressed={i18n.resolvedLanguage === code}
onClick={() => void i18n.changeLanguage(code)}
>
{label}
</button>
))}
</div>
</div>
);
}
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
const resources = {
en: { translation: { greeting: "Hello! Pick a language." } },
es: { translation: { greeting: "¡Hola! Elige un idioma." } },
};
void i18n.use(initReactI18next).init({
resources,
lng: "en",
fallbackLng: "en",
// React already escapes rendered values.
interpolation: { escapeValue: false },
});
export default i18n;
Changes to existing files
import Counter from "./components/Counter";+import LanguageSwitcher from "./components/LanguageSwitcher"; export default function App() { return ( <main className="app"> <h1 className="title">my-app</h1> <Counter />+ <LanguageSwitcher /> </main> ); }⋯ 1 unchanged lines
import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import App from "./App";+import "./i18n"; import "./index.css"; createRoot(document.getElementById("root")!).render(⋯ 5 unchanged lines
Project files
.gitignoreREADME.mdindex.htmlpackage.jsonsrc/App.tsxsrc/components/Counter.tsxsrc/components/LanguageSwitcher.tsxsrc/i18n.tssrc/index.csssrc/main.tsxtsconfig.jsonvite.config.ts