React – Render String with HTML tags as HTML

TRY IT LIVE

Click the button below to see a live example of this example that you can edit and try for yourself.

CODE SANDBOX

There are often times when you have a string with some HTML tags such as strong that you want to render as HTML on the DOM. Most solutions online recommend using dangerouslySetInnerHTML but that is dangerous as the name suggests. The proper way to render HTML from string is to use FormattedMessage from the formatjs library (react-intl version 5).

Here is a code example:

import React from "react";
import "./styles.css";
import { IntlProvider, FormattedMessage } from "react-intl";

export default function App() {
  return (
    <IntlProvider>
      <div className="App" style={{fontSize: 24}}>
        <FormattedMessage
          id="app.greeting"
          description="Bold text example"
          defaultMessage="Look here, I can include HTML tags in plain string and render them as HTML: <b>Bold</b>, <i>Italics</i> and <a>links too</a>."
          values={{
            b: (chunks) => <b>{chunks}</b>,
            i: (chunks) => <i>{chunks}</i>,
            a: (chunks) => (
              <a class="external_link" target="_blank" href="https://jiga.dev/">
                {chunks}
              </a>
            )
          }}
        />
      </div>
    </IntlProvider>
  );
}

This should show an output as:

Play with code sample in this link: https://codesandbox.io/s/react-render-html-from-props-string-c9ogm

You can also pass the defaultMessage and values as prop values from other components.

In the above example, I have used the version 5 from the react-intl library. In the previous versions, the API is a little different. Follow the official documentation for more options such as using child elements.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *