Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert HTML tag with injectIntl formatMessage using React-Intl?

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.

like image 859
tommychoo Avatar asked Mar 20 '19 03:03

tommychoo


People also ask

What does Intl formatMessage return?

formatMessage returns an array instead of a string #1681.

What is injectIntl in react?

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 .


1 Answers

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,
}
like image 63
martin Avatar answered Sep 25 '22 03:09

martin