2024 How to Localize your React App with react-i18next using nextjs
Leveraging i18next for React-Based Internationalization
Internationalization (i18n) is vital for expanding software reach across global markets. One of the most effective tools for this purpose in the JavaScript ecosystem is i18next. This article explores i18next, particularly its integration with React, and highlights its advantages, compatibility with various frameworks, and tips for enhancing localization efforts.
What is i18next?
i18next is a robust internationalization framework for JavaScript applications. It simplifies adding multilingual support to web, mobile, and desktop applications. The framework allows for dynamic translation management, making it easier to adapt applications to different languages and regions.
Advantages of i18next
- Ease of Integration
i18next is easy to integrate into existing projects and supports popular JavaScript frameworks such as React, Angular, and Vue. This versatility makes it a preferred choice for developers.
- Customization and Flexibility
i18next offers a modular structure that allows developers to use only the features they need. This high degree of customization ensures that the framework can fit a wide range of project requirements.
- Dynamic Loading of Translations
The framework supports the dynamic loading of translations, optimizing performance by fetching only the necessary language resources on demand.
- Pluralization and Contextualization
i18next includes built-in support for handling pluralization and contextualization, ensuring accurate language variations based on quantity or context.
- Support for Various File Formats
It supports multiple file formats for storing translations, including JSON and YAML, allowing flexibility in choosing the format that best fits the project’s needs.
- Rich Ecosystem
A thriving community and a rich ecosystem provide plugins, extensions, and support to enhance and extend i18next’s functionality, saving development time and effort.
- Multiple Backend Options
i18next supports various backends for storing and retrieving translations, such as in-memory, HTTP, and custom backends, enabling integration with different storage solutions.
- Active Development and Maintenance
Regular updates and improvements keep i18next current with best practices and evolving needs in web development.
React-i18next Integration
One of the most popular integrations of i18next is with React through the react-i18next
bindings. This combination allows for efficient internationalization within React components, facilitating dynamic language switching and seamless translation management.
Configure i18next in your React application(nextjs) by setting up the i18next instance and initializing it with the required options.
Example Code for React-i18next
Here's a step-by-step example of setting up and using react-i18next
in a React application:
1. Install Dependencies
First, install i18next
, react-i18next
, and next-i18next
for loading translations from the server:
npm install i18next react-i18next next-i18next
2. Initialize i18next
Create a file named next-i18next.config.js
for configuring and initializing i18next:
// next-i18next.config.js
const path = require('path'); // 添加这行来定义 path
module.exports = {
i18n: {
defaultLocale: 'en',
locales: ['en'], // add you langs here
// localeDetection: false, // default is true
},
localePath: path.resolve('./content/locales'), // here is your i18n file path
// ns: ['common','componentFeature'],
languageNames: {
'en': 'English',
},
}
// next.config.js
const { i18n } = require('./next-i18next.config')
module.exports = {
reactStrictMode: true,
async redirects() {
return [
];
},
i18n, // add this i18n config
};
3. Setup Translation Files
Create a locales
directory with subdirectories for each language (en
, de
, etc.). Inside each subdirectory, create a translation.json
file:
example:
-content
-locales
-en
-translation.json
-'other file if you have'.json
-de
-translation.json
-'other file if you have'.json
locales/en/translation.json
{
"welcome": "Welcome",
"description": "This is a sample description."
}
locales/de/translation.json
{
"welcome": "Willkommen",
"description": "Dies ist eine Beispielbeschreibung."
}
4. Wrap Your App with I18nextProvider
In your main like index.js
, App.js
or _app.tsx
file, wrap your application with appWithTranslation
:
import { appWithTranslation } from 'next-i18next';
function MyApp({ Component, pageProps }: AppProps) {
return (
...
);
}
export default appWithTranslation(MyApp) // wrap like this
5. Use Translation Hook in Components
Now, you can use the useTranslation
hook to translate strings in your components:
First, you shoul use serverSideTranslations
in page level file
export const getStaticProps: GetStaticProps = async ({ }) => {
return {
props: {
...(await serverSideTranslations(safeLocale, [
'translation', 'other'
])),
},
};
};
export default function Price() {
return (
<div>
<yourComponent/>
</div>
)
}
And then you in your Component
import React from 'react';
import { useTranslation } from 'next-i18next';
const MyComponent = () => {
const { t } = useTranslation('translation', 'other'); // translation is default here
return (
<div>
<h1>{t('welcome')}</h1>
<p>{t('description')}</p>
<p>{t('other:yourcontent')}</p> // use different namespace
</div>
);
};
export default MyComponent;