Application Internationalization (i18n)
Reach a global audience by making your application multilingual. Internationalization (i18n) is the process of designing an application so that it can be adapted to various languages and regions without engineering changes. By implementing i18n, you can include multi-language support and switch between locales with ease. Use the prompt below to guide an AI agent in setting up a robust translation system for your project.
You are an expert web developer specializing in internationalization (i18n). Your task is to implement a complete i18n solution for my application using the 'i18next' and 'react-i18next' libraries.
My Application Context:
- Framework: [e.g., Next.js, React with Vite]
- Primary Language: English (en)
- Target Languages: [e.g., Spanish (es), French (fr), German (de)]
Please perform the following steps:
1. **Install Dependencies:**
Add the required packages to the project: `i18next`, `react-i18next`, and `i18next-browser-languagedetector`.
2. **Create File Structure:**
Set up a `locales` directory inside the `src/` or `public/` folder. Inside `locales`, create a folder for each target language (e.g., `en`, `es`, `fr`). In each of these folders, create a `translation.json` file.
3. **Populate Translation Files:**
For each `translation.json` file, add a basic set of key-value pairs. Start with a simple greeting.
- In `en/translation.json`: `{ "welcome": "Hello, welcome to our application!" }`
- In `es/translation.json`: `{ "welcome": "Hola, ¡bienvenido a nuestra aplicación!" }`
- In `fr/translation.json`: `{ "welcome": "Bonjour, bienvenue sur notre application !" }`
4. **Configure i18n:**
Create a configuration file (e.g., `src/i18n.ts`) to initialize `i18next`.
- Use `i18next-browser-languagedetector` to automatically detect the user's browser language.
- Set English (`en`) as the fallback language.
- Configure the backend to load translation files from `/locales/{{lng}}/translation.json`.
- Ensure interpolation is escaped to prevent XSS attacks (`escapeValue: false` is needed for React).
5. **Wrap the Application:**
In the main application entry point (e.g., `main.tsx` or `_app.tsx`), wrap the root component with the `I18nextProvider`.
6. **Create a Language Switcher Component:**
Build a simple React component that allows the user to switch the language. It should contain buttons for each target language which, when clicked, call the `i18n.changeLanguage()` function.
7. **Demonstrate Usage:**
Modify the main page component to use the `useTranslation` hook. Replace a hardcoded string (like a welcome message) with the `t('welcome')` function to display the translated text.
Provide the complete, updated code for all new and modified files, including the i18n config, the language switcher component, and the updated main page.