2

I am using React Intl for my internalization and have to write this.props.intl.formatMessage({id: 'some.message.id'}, values) to get a translated string in the render() method. Now, how should a decorator look like to provide a shortcut function for this so I could do like _t('some.message.id', values) or similar?

I know I could probably just write another class that extends React.Component or wrap the component in another class or whatsoever, but I'd like to do it with decorators (for learning and understanding purposes), if it's possible to do so.

Maxim Zubarev
  • 2,403
  • 2
  • 29
  • 48

1 Answers1

0

Here's something to get you started:

function mydecorator(target, key, descriptor) {
  const method = descriptor.value;

  descriptor.value = function(...args) {
    args.push(this.props.intl.formatMessage); // may need `.bind(...)`
    return method.apply(this, args);
  }
}

To use:

@mydecorator
render(_t) {
  ...
}

The decorator replaces render with a function that pushes a reference to this.props.intl.formatMessage to the list of arguments that subsequently get passed in a call to the original render (which, AFAIK, doesn't take arguments, so you could probably shorten the code by taking out the args variable).

You can of course push an intermediate function as argument that will do better handling of the id argument, etc.

robertklep
  • 198,204
  • 35
  • 394
  • 381