Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intl.formatMessage not working - react-intl

I am trying to do language translation using react-intl. When I use this <FormattedMessage id='importantNews' />, it is working perfect. But when I use the following code with intl.formatMessage(), it is not working and throwing some errors. I don't know what is wrong in it.

import { injectIntl, FormattedMessage } from 'react-intl';

function HelloWorld(props) {
  const { intl } = props;
  const x = intl.formatMessage('hello') + ' ' + intl.formatMessage('world'); //not working
  const y = <FormattedMessage id='hello' />; //working
  return (
    <button>{x}</button>
  );
}

export default injectIntl(HelloWorld);

My root component is like this,

import ReactDOM from 'react-dom';
import { addLocaleData, IntlProvider } from 'react-intl';
import enLocaleData from 'react-intl/locale-data/en';
import taLocaleData from 'react-intl/locale-data/ta';

import HelloWorld from './hello-world';

addLocaleData([
  ...enLocaleData,
  ...taLocaleData
]);

const messages = {
  en: {
    hello: 'Hello',
    world: 'World'
  },
  ta: {
    hello: 'வணக்கம்',
    world: 'உலகம்'
  }
};

ReactDOM.render(
  <IntlProvider key={'en'} locale={'en'} messages={messages['en']}>
    <HelloWorld />
  </IntlProvider>,
  document.getElementById('root')
);

Can someone help me to solve this issue? Thanks in advance.

like image 919
Abraham Gnanasingh Avatar asked Jun 29 '17 18:06

Abraham Gnanasingh


3 Answers

After trying and failing with dynamic values, I figured out that if const intlKey = "something"

{intl.formatMessage({ id: intlKey })} //this doesn't work
{intl.formatMessage({ id: `${intlKey}` })} //this works
<IntlMessages id={intlKey} /> //this doesn't work
<IntlMessages id={`${intlKey}`} /> //this works

Thus stringify your value (even if sure that it's a string) for intl to work.

like image 189
its4zahoor Avatar answered Nov 03 '22 02:11

its4zahoor


You need to call formatMessage with MessageDescriptor, not just id:

const x = intl.formatMessage({id: 'hello'}) + ' ' + intl.formatMessage({id: 'world'});

To better remember this - component is called with prop id:

<FormatMessage id="Hello" />

Props are in fact a key-value dictionary:

// this is the same as above
<FormatMessage {...{id: 'hello'}} />

Now, formatMessage function accepts the same props as FormatMessage component:

formatMessage({id: 'hello'})
like image 19
Tomáš Ehrlich Avatar answered Nov 03 '22 00:11

Tomáš Ehrlich


Besides, seems like you are missing default value for it.

 <FormattedMessage id="footer.table_no" defaultMessage="Hello" />
like image 1
Zhihong LU Avatar answered Nov 03 '22 00:11

Zhihong LU