0

For localization, I am using React-intl. I am exporting below(intl.js) -

import { injectIntl } from 'react-intl';

const Intl = injectIntl(({ intl, children }: any) => children(intl));

const t = (
id: string | Array<string>,
values: Object | void,
) => <Intl>{i => i.formatMessage({ id }, values)}</Intl>;

export default t;

And in the place where I need to translate strings, I am importing above file like -

import t from '../../../components/intl.js';

I have the en.json file which have the translations defined, like -

"tri-pod":"tripod"

I am able to use translation like -

<span>{t`tri-pod`}</span>

Where I am facing problem is how to use the translations while sending as props like given below-

<mylabel label="tripod"></mylabel>

Adding label={ttri-pod} errors out. What is the correct way to send the translated string itself as props?

ramesh en
  • 93
  • 1
  • 2
  • 10

1 Answers1

0

The problem with t helper is that it doesn't output translated string as it's expected from i18n helper but outputs <Intl> element. This limits its possible uses.

In order to get translated string with t, a component likely should be enhanced with higher-order component:

const withT = Comp => injectIntl(({ intl, ...props}) => <Comp
  t={(id, values) => intl.formatMessage({ id }, values)}
  {...props}
/>);

Then t helper will be available as t prop in enhanced components.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565