i18next / react-i18next

Internationalization for react done right. Using the i18next i18n ecosystem.
https://react.i18next.com
MIT License
9.3k stars 1.03k forks source link

Correct import of react-i18next #385

Closed mrlubos closed 6 years ago

mrlubos commented 6 years ago

Hey,

Wanted to ask if this is a correct usage of react-i18next as my linter was warning me about duplicate imports.

import { translate } from 'react-i18next';

class ComponentOne extends Component {
  render() {
    const { t } = this.props;
    // ...
  }
}

export default translate('translations')(connect(
  mapStateToProps,
  mapDispatchToProps,
)(ComponentOne));
import { translate } from 'react-i18next';

class ComponentTwo extends Component {
  render() {
    const { t } = this.props;
    // ...
  }
}

export default translate('translations')(connect(
  mapStateToProps,
  mapDispatchToProps,
)(ComponentTwo));

ComponentTwo is a child of ComponentOne, but not the first child.

The whole app is rendered like so.

import React from 'react';
import { Provider } from 'react-redux';
import { I18nextProvider } from 'react-i18next';
import { ConnectedRouter } from 'react-router-redux';
import { store, history } from 'config/store';
import ReactDOM from 'react-dom';

import App from './ComponentOne';
import i18n from './i18n';

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter ={history}>
      <I18nextProvider i18n={ i18n }>
        <ComponentOne />
      </I18nextProvider>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

I understand the provider should make the t() method available in every child component, correct? However, neither this.props nor this.context in render() method of ComponentTwo included this function. Thank you!

jamuhl commented 6 years ago

Provider enables i18n instance in react context. Hoc pass down t function from i18n to component.

Beside that i don't know why the linter is complaining...there is no double import in one file.

mrlubos commented 6 years ago

@jamuhl I assume it's because I call import { translate } from 'react-i18next'; in 2 places or call it, didn't explore further. Is my syntax correct then? Once I turned off the linter rule, everything works as expected, although I should be able to access the t() method from every child component without importing translate again and again, no?

jamuhl commented 6 years ago

no...you need to use the hoc on every component

the linter should not complain...at least not if using webpack and file per component...

depends on your build process

mrlubos commented 6 years ago

Awesome, thanks for explaining!