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');
The withTranslation HOC will trigger a Suspense if not ready (eg. pending load of translation files). You can set useSuspense to false if prefer not using Suspense.
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
// load a specific namespace// the t function will be set to that namespace as defaultwithTranslation('ns1')(MyComponent);// inside your component MyComponentthis.props.t('key'); // will be looked up from namespace ns1// load multiple namespaces// the t function will be set to first namespace as defaultwithTranslation(['ns1','ns2','ns3'])(MyComponent);// inside your component MyComponentthis.props.t('key'); // will be looked up from namespace ns1this.props.t('key', { ns:'ns2' }); // will be looked up from namespace ns2
Overriding the i18next instance
// passing in an i18n instance// use only if you do not like the default instance// set by i18next.use(initReactI18next) or the I18nextProviderimport i18n from'./i18n';constExtendedComponent=withTranslation('ns1')(MyComponent);<ExtendedComponenti18n={i18n} />
Not using Suspense
// use tReady prop in MyComponent to check if translations// are already loaded or notconstExtendedComponent=withTranslation()(MyComponent);<ExtendedComponentuseSuspense={false} />
Not using Suspense you will need to handle the not ready state yourself by eg. render a loading component as long !props.tReady . Not doing so will result in rendering your translations before they loaded which will cause save missing be called although translations exist (just yet not loaded).
How to
use ref (>= v10.6.0)
You can use forwardRefs like:
constWrapped=withTranslation('translation', { withRef:true })(MyComponent);// then pass a ref in your render method likeconstmyRef=React.createRef();<Wrappedref={myRef} />;// use myRef.current to access it
hoist non-react statics
The HOC does not hoist statics itself so you might append those statics manually or by using a module.