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

How to use the t() from react-i18next outside of a component

1个答案

1

When implementing internationalization in a React project using the react-i18next library, it is common to obtain the t function within components via the useTranslation Hook or the withTranslation Higher-Order Component for translating text. However, when needing to use the t function outside components—such as in a module or utility function—you cannot utilize these React-specific methods.

To use the t function outside components, directly access it from the i18next instance. Here is a step-by-step example:

Step 1: Initialize i18next

First, ensure i18next is initialized in your application's entry file:

javascript
import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; i18n .use(initReactI18next) .init({ resources: { en: { translation: { "welcome_message": "Welcome to React" } }, fr: { translation: { "welcome_message": "Bienvenue à React" } } }, lng: "en", fallbackLng: "en", interpolation: { escapeValue: false } }); export default i18n;

Step 2: Use i18next Outside Components

Once i18next is instantiated in your application, you can directly use it in any module:

javascript
import i18n from './i18n'; // Ensure you import your i18n configuration from the correct path function getWelcomeMessage() { return i18n.t('welcome_message'); } console.log(getWelcomeMessage()); // This will print "Welcome to React" or "Bienvenue à React" based on the current language setting

Example

Suppose you have a utility function file utils.js for handling text internationalization:

javascript
import i18n from './i18n'; export function formatError(errorCode) { return i18n.t(`error_messages.${errorCode}`); }

This approach enables you to use the t function for text internationalization anywhere in the application, without relying on React component lifecycle or context.

Conclusion

Using the i18next instance to directly obtain and utilize the t function outside components is a highly effective and straightforward method, particularly when handling internationalization in pure JavaScript modules. This approach maintains code clarity and modularity, simplifying the testing and maintenance of internationalization features.

2024年6月29日 12:07 回复

你的答案