rmdort / react-redux-multilingual

A simple and slim multi-lingual component for React with Redux without react-intl or react-i18n
41 stars 14 forks source link

Transform withTranslate() method as a decorator #13

Closed Jeremboo closed 6 years ago

Jeremboo commented 6 years ago

Hi again,

It could be useful to transform the method withTranslate() to permit its use as a decorator.

import { withTranslate } from 'react-redux-multilingual'

// ----------------------------------
// Old version
const App = ({ translate }) = {
  return (
    <div>
      {translate('hello', { name: 'John Doe' })}
    </div>
  )
}
export default withTranslate(App)

// ----------------------------------
// To that
@withTranslate()
const App = ({ translate }) = {
  return (
    <div>
      {translate('hello', { name: 'John Doe' })}
    </div>
  )
}
export default App

It improve the usage into workflow with decorators (or typescript projets) without break the syntax.

Transform the current method into decorator is pretty easy. You can see the patch I made into my project :

import { withTranslate } from 'react-redux-multilingual'
export default () => (WrapperComponent) => withTranslate(WrapperComponent);

A little update who does not add a big breaking change and can be more user friendly into some projets. Decorators can also be written traditionally: withTranslate()(App).

rmdort commented 6 years ago

You can still use withTranslate as a decorator.

Install babel plugin

npm install babel-plugin-transform-decorators-legacy --save-dev

In your .babelrc file add,

{
  "presets": ["env", "stage-0", "react"],
  "plugins": ["transform-decorators-legacy"]
}

And use it like this

@withTranslate
class App extends React.Component {
  render () {
    const { translate } = this.props
    return (
      <div>
        <p>Hey there</p>
        {translate('hello')}
      </div>
    )
  }
}

Do note that, you can only add decorators on class instances and not on functional components as per the spec

Jeremboo commented 6 years ago

My bad... I used parentheses to declare my decorator: @withTranslate() That's why it did not work. Thank you very much and sorry for the inconvenience.