withTranslation (HOC)
What it does
The withTranslation is a classic HOC (higher order component) and gets the t function and i18n instance inside your component via props.
import React from 'react';
import { withTranslation } from 'react-i18next';
function MyComponent({ t, i18n }) {
return <p>{t('my translated text')}</p>
}
export default withTranslation()(MyComponent);import React from 'react';
import { withTranslation } from 'react-i18next';
function MyComponent({ t, i18n }) {
return <p>{t($ => $['my translated text'])}</p>
}
export default withTranslation()(MyComponent);While you most time only need the t function to translate your content you also get the i18n instance to eg. change the language.
i18n.changeLanguage('en-US');When to use?
Use the withTranslation HOC to wrap any component (class or function) to access the translation function or i18n instance.
withTranslation params
Loading namespaces
Overriding the i18next instance
Not using Suspense
How to
use ref (>= v10.6.0)
You can use forwardRefs like:
hoist non-react statics
The HOC does not hoist statics itself so you might append those statics manually or by using a module.
Use hoist-non-react-statics yourself:
Or simply hoist the one/two statics yourself:
use TypeScript with class components
To get proper type annotations while using TypeScript, import the interface WithTranslation and extend it with your own props interface.
Last updated