Render Content with Markup Using react-intl FormattedHTMLMessage

Damon Bauer
InstructorDamon Bauer
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 4 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.

Dean
Dean
~ 7 years ago

What if I want the user to "select" the preferred language rather than basing it on their browser locale. What is the mechanism to achieve this? Say, for example, they selected the language from the dropdown or I pass it from the backend.

Nikolai
Nikolai
~ 7 years ago

What if I want the user to "select" the preferred language rather than basing it on their browser locale. What is the mechanism to achieve this? Say, for example, they selected the language from the dropdown or I pass it from the backend.

I guess, you can always set the global javascript constant in you html markup (which is generated on your server), like: <code><script>var _USER_LANGUAGE = "en-EN"</script></code> and get to this var on client side.

Markdown supported.
Become a member to join the discussionEnroll Today