React-Intl How to use FormattedMessage in input placeholder

Bryan picture Bryan · Sep 22, 2016 · Viewed 69.3k times · Source

I'm unsure how to get the values from

<FormattedMessage {...messages.placeholderIntlText} />

into a placeholder format like input:

<input placeholder={<FormattedMessage {...messages.placeholderIntlText} />} />

as it would return [Object object] in the actual placeholder. Is there a way to get the actual correct value?

Answer

lsoliveira picture lsoliveira · Sep 28, 2016

The <Formatted... /> React components in react-intl are meant to be used in rendering scenarios and are not meant to be used in placeholders, alternate text, etc. They render HTML, not plain text, which is not useful in your scenario.

Instead, react-intl provides a lower level API for exactly this same reason. The rendering components themselves use this API under the hoods to format the values into HTML. Your scenario probably requires you to use the lower level formatMessage(...) API.

You should inject the intl object into your component by using the injectIntl HOC and then just format the message through the API.

Example:

import React from 'react';
import { injectIntl, intlShape } from 'react-intl';

const ChildComponent = ({ intl }) => {
  const placeholder = intl.formatMessage({id: 'messageId'});
  return(
     <input placeholder={placeholder} />
  );
}

ChildComponent.propTypes = {
  intl: intlShape.isRequired
}

export default injectIntl(ChildComponent);

Please note that I'm using some ES6 features here, so adapt according to your setup.