Managing Translations
Step 1: Organize Translation Files
Create a locales
folder in your public
directory:
Step 2: Example Translation Files
English (en/translation.json
):
Spanish (es/translation.json
):
{ "welcome": "Bienvenido", "description": "Esta es una aplicación internacionalizada." }
Step 3: Use Translations in Components
Use the useTranslation
hook to fetch and display translations:
import React from "react";
import { useTranslation } from "react-i18next";
const WelcomeMessage = () => {
const { t } = useTranslation();
return (
<div>
<h1>{t("welcome")}</h1>
<p>{t("description")}</p>
</div>
);
};
export default WelcomeMessage;
Step 4: Dynamic Language Switching
Add a language switcher to allow users to change the language dynamically:
import React from "react";
import { useTranslation } from "react-i18next";
const LanguageSwitcher = () => {
const { i18n } = useTranslation();
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<div>
<button onClick={() => changeLanguage("en")}>English</button>
<button onClick={() => changeLanguage("es")}>Español</button>
</div>
);
};
export default LanguageSwitcher;
Step 5: Test Your Implementation
- Start your development server.
- Verify that translations change when switching languages.
With these steps, you can successfully set up internationalization for your React application and manage translations efficiently.