When using i18next for internationalization, we often need to include dynamic content in text, such as the user's name or other data retrieved from React's context.
To accomplish this, we can utilize i18next's interpolation capabilities along with React's Context API.
First, we need to set up React's Context. Here's a simple example, assuming we have a UserContext to store user information:
jsximport React, { createContext, useContext } from 'react'; const UserContext = createContext(null); const UserProvider = ({ children }) => { const user = { name: '张三' }; // Assume this is user data from an API return <UserContext.Provider value={user}>{children}</UserContext.Provider>; }; const useUser = () => useContext(UserContext);
Then, within our components, we can use the useUser Hook to access the current user data and incorporate the username into the translation string using i18next's interpolation feature:
jsximport React from 'react'; import { useTranslation } from 'react-i18next'; import { useUser } from './UserContext'; // Import the defined useUser const Greeting = () => { const { t } = useTranslation(); const { name } = useUser(); return <h1>{t('helloUser', { name })}</h1>; };
In the i18next resource file, we must define a string that includes interpolation:
json{ "en": { "translation": { "helloUser": "Hello, {{name}}" } }, "zh": { "translation": { "helloUser": "你好,{{name}}" } } }
As a result, when the Greeting component renders, it fetches the current user's name from UserContext and inserts the username into the translation string using i18next's t function. This achieves dynamic interpolation of React context variables within i18next.
One key benefit of this approach is that it enables flexible integration of arbitrary context data into translation strings, making it ideal for scenarios where personalized user information or other dynamic context data needs to be displayed.