I have a react-intl package issue. I am using an injectIntl way to use props in the component. Pure String is fine, but it will not work if I wrapped the HTML tag.
Pure String Success Case
const _tableNoText = intl.formatMessage(
{ id: 'footer.table_no' },
{ value: basket.table }
);
//console -> Table 1
Pure String with HTML Tag Fail Case
const _tableNoText = intl.formatMessage(
{ id: 'footer.table_no' },
{ value: <b>basket.table</b> }
);
// console -> Table [object object]
If I change the formatMessage
to formatHTMLMessage
, it will output the same above result, how should I fix that?
Thanks all very much.
formatMessage returns an array instead of a string #1681.
injectIntl HOC This function is exported by the react-intl package and is a High-Order Component (HOC) factory. It will wrap the passed-in React component with another React component which provides the imperative formatting API into the wrapped component via its props .
When you're using { value: <b>basket.table</b> }
you're in fact creating React component b
which is an ordinary JavaScript object. This step is just hidden from you by tsx
(or jsx
) compiler.
So if you want to render HTML you have to wrap the actual HTML string with quotes, then translate the string and then let React unwrap (or turn) the HTML string into DOM elements.
const translated = intl.formatMessage(
{ id: 'footer.table_no' },
{ value: '<strong>STRONG</strong>' }
);
return (
<div dangerouslySetInnerHTML={{__html: translated}} />
)
If you want to interpolate basket.table
just pass it as another value:
...
{
value: '<strong>STRONG</strong>',
table: basket.table,
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With