Render Content with Markup Using react-intl FormattedHTMLMessage

Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

In this lesson, we’ll use the react-intl FormattedHTMLMessage component to display text with dynamic values along with other HTML elements to create emphasis on a piece of text.

Note: FormattedHTMLMessage should be used sparingly because react-intl cannot intelligently update the component by re-rendering only pieces that have changed. Instead, it has to re-render the entire component. If possible, use a FormattedMessage component instead, and wrap that component with HTML markup.

[00:01] Let's start by adding a string to our messages file that will tell the user that merchant links will open in the new window. Notice that I'm embedding markup directly in the string. I've also added a placeholder of numMerchants.

[00:19] In our bookDetail component, let's import formattedHTMLMessage from React Intl. Since we're going to be displaying a message about opening links in the new window, let's first add a target blank to those merchant links.

[00:34] We'll just say target='_blank' and we'll go below those merchant links. Now let's add a formattedHTMLMessage component. We'll pass an ID prop of detail.window, and a values prop of numMerchants, and that will be set to book.merchants.link.

[01:05] The link of this books.merchants array will be passed to numMerchants, which will replace the token in our messages file. Now you can see that we're displaying this text in each language, and it's formatted correctly as well.