JavaScript Using react-i18next within a class component using react-i18next,react in i18next,use translation react i18next

I am trying to translate my application using react-i18next. I know how to use it with simple const components, but not within a class.

I'm working with the I18nextProvider. This is my App.js file.

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { I18nextProvider } from 'react-i18next';
import i18next from 'i18next';
// eslint-disable-next-line import/no-extraneous-dependencies
import { hot } from 'react-hot-loader';
import 'bootstrap/dist/css/bootstrap.css';
import '../../scss/app.scss';
import Router from './Router';
import store from './store';
import ScrollToTop from './ScrollToTop';
import { config as i18nextConfig } from '../../translations';

i18next.init(i18nextConfig);

class App extends Component {
  constructor() {
    super();
    this.state = {
      loading: true,
      loaded: false,
    };
  }

  componentDidMount() {
    window.addEventListener('load', () => {
      this.setState({ loading: false });
      setTimeout(() => this.setState({ loaded: true }), 500);
    });
  }

  render() {
    const { loaded, loading } = this.state;
    return (
      <Provider store={store}>
        <BrowserRouter basename="/easydev">
          <I18nextProvider i18n={i18next}>
            <ScrollToTop>
              {!loaded &&
                <div className={`load${loading ? '' : ' loaded'}`}>
                  <div className="load__icon-wrap">
                    <svg className="load__icon">
                      <path fill="#4ce1b6" d="M12,4V2A10,10 0 0,0 2,12H4A8,8 0 0,1 12,4Z" />
                    </svg>
                  </div>
                </div>
              }
              <div>
                <Router />
              </div>
            </ScrollToTop>
          </I18nextProvider>
        </BrowserRouter>
      </Provider>
    );
  }
}

export default hot(module)(App);

Now using it within a const based component is quite easy. Here is an example:

import React from 'react';
import { Card, CardBody, Col } from 'reactstrap';
import HeartOutlineIcon from 'mdi-react/HeartOutlineIcon';
import { translate } from 'react-i18next';
import PropTypes from 'prop-types';

const InfoCard = ({ t }) => (
  <Col md={12} xl={3} lg={6} sm={12} xs={12}>
    <Card>
      <CardBody className="dashboard__health-chart-card">
        <div className="card__title">
          <h5 className="bold-text">{t('dashboard_fitness.heartrate')}</h5>
        </div>
        <div className="dashboard__health-chart">
          <div className="dashboard__health-chart-info">
            <HeartOutlineIcon style={{ fill: '#ff4861' }} />
            <p className="dashboard__health-chart-number">96</p>
            <p className="dashboard__health-chart-units">b/min</p>
          </div>
        </div>
      </CardBody>
    </Card>
  </Col>
);

InfoCard.propTypes = {
  t: PropTypes.func.isRequired,
};

export default translate('common')(InfoCard);

As you can see I just import the translate from the react-i18next and I'm almost ready to go with the t function.

How can I achieve the same within a class component? I want to implement it in this class:

/* eslint-disable react/no-typos */
import React, { PureComponent } from 'react';
import { DropdownItem, DropdownMenu, DropdownToggle, UncontrolledDropdown } from 'reactstrap';
import { translate } from 'react-i18next';

import MenuDownIcon from 'mdi-react/ChevronDownIcon';
import MagnifyIcon from 'mdi-react/MagnifyIcon';

class TradesTableControls extends PureComponent {
  constructor() {
    super();
    this.state = {
      rows: 10,
    };
  }

  changeRowAmount = (rows) => {
    switch (rows) {
      case 10:
        this.setState({ rows: 10 });
        break;
      case 25:
        this.setState({ rows: 25 });
        break;
      case 50:
        this.setState({ rows: 50 });
        break;
      case 100:
        this.setState({ rows: 100 });
        break;
      default:
        this.setState({ rows: 10 });
        break;
    }
  };

  render() {
    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>
    );
  }
}

export default translate('common')(TradesTableControls);

I'm quite new to React and ES6, but I was unable to find the solution online. Would really appreciate any help!

Thanks!

Answer:1

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>
    );
  }
Answer:2

I'm trying to efficiently make a key-value tour in an array in reactjs. However, I do not know how to display the "key" array without creating another map function. const equipos = [ { key: [ ...

I'm trying to efficiently make a key-value tour in an array in reactjs. However, I do not know how to display the "key" array without creating another map function. const equipos = [ { key: [ ...

Here is the code: function fil(val) { console.log('fil'); // never written to console when run in greasemonkey return true; } var temp = unsafeWindow.someobject; console.log(temp); // looks fine ...

Here is the code: function fil(val) { console.log('fil'); // never written to console when run in greasemonkey return true; } var temp = unsafeWindow.someobject; console.log(temp); // looks fine ...

  1. what could stop you from getting a passport
  2. what could stop you from getting pregnant
  3. what could stop the ocean currents
  4. what could stop my period
  5. what could stop a car from starting
  6. what would stop diarrhea
  7. what would stop you from being drafted
  8. what could stop your car from starting
  9. what could stop me from getting pregnant
  10. what would stop you from getting drafted
  11. what could stop implantation
  12. what could stop global warming
  13. what could stop climate change
  14. what could stop your period from coming
  15. what could stop your period
  16. what could stop menstruation
  17. what could stop brexit
  18. what could stop periods
  19. what could stop ovulation
  20. what could stop me getting a mortgage

Is that me doing something wrong or some known bug of using scope operator ([...arr]) with Date()/Date.UTC() constructor? What confuses me: x = [2015,5,1]; //(3) [2015, 5, 1] new Date(2015, 5, 1); //...

Is that me doing something wrong or some known bug of using scope operator ([...arr]) with Date()/Date.UTC() constructor? What confuses me: x = [2015,5,1]; //(3) [2015, 5, 1] new Date(2015, 5, 1); //...

I can't seem to pass Vue data into Vue component from an inline template. I'm getting this error instead: vue.min.js: Uncaught TypeError: Cannot read property 'type' of undefined Below is my ...

I can't seem to pass Vue data into Vue component from an inline template. I'm getting this error instead: vue.min.js: Uncaught TypeError: Cannot read property 'type' of undefined Below is my ...

  1. canvas
  2. canada
  3. cancelled
  4. canceled vs cancelled
  5. cancun
  6. canada goose
  7. cane corso
  8. canes
  9. canadian prime minister
  10. cancun flights
  11. canker sore
  12. candy
  13. cancer
  14. canon
  15. canvas prints
  16. cancer sign
  17. candace owens
  18. canada news
  19. candytopia
  20. canlis