Using react-i18next within a class component
Just like t
is available as props in a functional
component, you can access it from props
in a class component after wrapping TradesTableComponent
with translate HOC
. All you need to do is destructure
it from props in render method like
const { t } = this.props;
Relevant code
render() { const { t } = this.props; return ( <div className="trades-table__controls-wrap"> <div className="trades-table__controls"> <UncontrolledDropdown> <DropdownToggle className="icon icon--right" outline size="sm"> <p> {t('history.controls.show')} {this.state.rows} {t('history.controls.results')} <MenuDownIcon /> </p> </DropdownToggle> <DropdownMenu className="dropdown__menu"> <DropdownItem onClick={() => this.changeRowAmount(10)}>10</DropdownItem> <DropdownItem onClick={() => this.changeRowAmount(25)}>25</DropdownItem> <DropdownItem onClick={() => this.changeRowAmount(50)}>50</DropdownItem> <DropdownItem onClick={() => this.changeRowAmount(100)}>100</DropdownItem> </DropdownMenu> </UncontrolledDropdown> </div> <div className="trades-table__controls-right"> <div className="trades-table__control-search"> <input placeholder="Search" /> <div className="trades-table__control-search-icon"><MagnifyIcon /></div> </div> </div> </div> ); }
Currently (ie 2021) the docs suggest the packaged HOC withTranslation()
:
import React from 'react';import { withTranslation } from 'react-i18next';class MyComponent extends Component { return <p>{this.props.t('key')}</p>}export default withTranslation()(MyComponent);
If you like to use namespaces then export:
export default withTranslation('namespace')(MyComponent);
Ref: official docs.
Here's a working example of how to use translation
in a class-based component in React Native.
import { withTranslation } from 'react-i18next';
class PersonalScreen extends React.Component { render() { const { t } = this.props; return ( <Text>{t('Translate this text')}</Text> ) }}export default withTranslation()(PersonalScreen)