withTranslation() Higher-order Component
Learn how to access the translation function or i18n instance inside class components.
We'll cover the following
What is the withTranslation()
HOC?
The withTranslation()
function will create a higher-order component, which we can pass to the component that is supposed to be translated. The t
and i18n
props will be passed to this component. To do this, we import the function as a named export from the react-i18next
package:
import { withTranslation } from 'react-i18next';
Once imported, we call the function and obtain a higher-order component. We then pass this higher-order component to the component that we want to use to access the translated values. If we are using namespaces, we can also pass the namespace we want to use to the withTranslation()
function:
// Without namespaces (using the default value):
const TranslatedComponent = withTranslation()(TranslatedComponent);
// Using a single namespace:
const TranslatedComponent = withTranslation('namespace')(TranslatedComponent);
// Using multiple namespaces:
const TranslatedComponent = withTranslation(['namespace1', 'namespace2'])(
TranslatedComponent
);
It can prove useful to extract components into their own files and wrap them with the withTranslation()
higher-order component when they are exported:
// Greeting.js
class Greeting extends React.Component {
render() {
const { t } = this.props;
return <div>{t('greeting')}</div>;
}
}
export default withTranslation()(Greeting);
We can then immediately import the translated component:
import Greeting from './Greeting.js';
Not only have we imported the actual component, but we have also gained access to the extended props t
, i18n
, and tReady
via i18next
.
The t
function forms the central function for everything related to translations. It is passed a translation key and will return the translated value to us, based on the selected language.
Code examples
Let’s see the above functionality in action:
Get hands-on with 1400+ tech skills courses.