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);

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

Overriding the i18next instance

Not using Suspense

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:

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