乐闻世界logo
搜索文章和话题

How to change language with i18next in React

1个答案

1

Implementing language switching in a React project using i18next is an excellent choice, as i18next is a powerful internationalization framework that supports multiple language switching and resource management. Below, I'll walk you through how to integrate and use i18next in React.

Step 1: Install Required Packages

First, install i18next and react-i18next in your React project using npm or yarn:

bash
npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector

or

bash
yarn add i18next react-i18next i18next-http-backend i18next-browser-languagedetector

Here, i18next-http-backend is used for loading language files, and i18next-browser-languagedetector automatically detects the user's browser language.

Step 2: Configure i18next

Create a configuration file, such as i18n.js, to initialize and configure i18next:

javascript
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import HttpApi from 'i18next-http-backend'; import LanguageDetector from 'i18next-browser-languagedetector'; i18n .use(initReactI18next) // Bind via react-i18next .use(HttpApi) // Load language packages .use(LanguageDetector) // Automatically detect language .init({ supportedLngs: ['en', 'de', 'fr'], // Supported languages fallbackLng: 'en', // Default language detection: { order: ['querystring', 'cookie', 'localStorage', 'path', 'subdomain'], caches: ['cookie'], }, backend: { loadPath: '/assets/locales/{{lng}}/translation.json', // Language package path }, }); export default i18n;

Step 3: Create Language Files

Create language files in your project. For example, place the English translation in public/assets/locales/en/translation.json:

json
{ "welcome": "Welcome to React" }

For German public/assets/locales/de/translation.json:

json
{ "welcome": "Willkommen bei React" }

Step 4: Use Translation

In your React component, use the useTranslation Hook to call i18next:

javascript
import React from 'react'; import { useTranslation } from 'react-i18next'; function App() { const { t, i18n } = useTranslation(); const changeLanguage = (language) => { i18n.changeLanguage(language); }; return ( <div> <h1>{t('welcome')}</h1> <button onClick={() => changeLanguage('de')}>Deutsch</button> <button onClick={() => changeLanguage('en')}>English</button> </div> ); } export default App;

With this implementation, users can switch languages by clicking buttons, and interface text will automatically update to the corresponding language translation.

Summary

By following these steps, you can flexibly implement multilingual functionality in your React application. i18next provides rich configuration options and automatic language detection, making it ideal for production-ready internationalization projects.

2024年8月8日 15:13 回复

你的答案