Ir al contenido

i18n con react-i18next

Setup mínimo de i18n en React con react-i18next, con traducciones en inglés y español.

Ventana de terminal
npm install i18next react-i18next i18next-browser-languagedetector
src/i18n/en/common.json
{
"greeting": "Hello, {{name}}!",
"cart": {
"itemCount": "{{count, plural, one {# item} other {# items}}} in your cart"
}
}
src/i18n/es/common.json
{
"greeting": "¡Hola, {{name}}!",
"cart": {
"itemCount": "{{count, plural, one {# artículo} other {# artículos}}} en tu carrito"
}
}
src/i18n/index.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import enCommon from './en/common.json';
import esCommon from './es/common.json';
i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
supportedLngs: ['en', 'es'],
defaultNS: 'common',
resources: {
en: { common: enCommon },
es: { common: esCommon },
},
interpolation: { escapeValue: false },
});
export default i18n;
src/components/Cart.tsx
import { useTranslation } from 'react-i18next';
type CartProps = { userName: string; itemCount: number };
export function Cart({ userName, itemCount }: CartProps) {
const { t, i18n } = useTranslation();
return (
<section>
<h1>{t('greeting', { name: userName })}</h1>
<p>{t('cart.itemCount', { count: itemCount })}</p>
<label>
Idioma
<select
value={i18n.language}
onChange={(e) => i18n.changeLanguage(e.target.value)}
>
<option value="en">English</option>
<option value="es">Español</option>
</select>
</label>
</section>
);
}
  • Las claves son idénticas entre locales — solo cambian los valores.
  • La sintaxis ICU de plurales maneja one / other automáticamente.
  • Ver las guías de i18n compartidas para convenciones cross-framework.