React-i18next is designed to be used within a React component, as it depends on the React Context API to manage translations. However, it is possible to use the i18next library directly within a vanilla JavaScript function, without React.
Here's an example:
import i18next from 'i18next';
function translate(key) {
return i18next.t(key);
}
// Usage:
console.log(translate('welcome')); // "Welcome"
console.log(translate('greeting', { name: 'John' })); // "Hello John"
In this example, i18next
is imported and used directly to translate keys. The translate
function takes a key as an argument and returns the corresponding translation. You can also pass in additional options as a second argument, such as variables to interpolate into the string.
Keep in mind that this approach does not provide the benefits of React-i18next's intuitive syntax or automatic re-rendering on language changes. If you need those features, you'll want to use React components.
Asked: 2022-05-23 11:00:00 +0000
Seen: 9 times
Last updated: May 24 '22