React-Intl How to use FormattedMessage in input placeholder
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?
Solution 1:
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.
Solution 2:
- You can use
intl
prop frominjectIntl
HoC - You can also provide function as child component:
<FormattedMessage {...messages.placeholderIntlText}>
{(msg) => (<input placeholder={msg} />)}
</FormattedMessage>
Solution 3:
For Input placeholder for more details
<FormattedMessage id="yourid" defaultMessage="search">
{placeholder=>
<Input placeholder={placeholder}/>
}
</FormattedMessage>