How to use HTML entities without dangerouslySetInnerHTML in React

There may be times when you will want to render a string with HTML entities in it in your React application. An HTML entity is a piece of text (string) that begins with an ampersand (&) and ends with a semicolon (;). They are frequently used to display reserved and invisible characters, like non-breaking spaces ( ) or soft hyphens (​) for marking line breaking opportunities.

To render these characters, you need to use dangerouslySetInnerHTML:

function createMarkup(myTextFromDatabase) {
  return {__html: myTextFromDatabase};
}

function MyComponent({myTextFromDatabase}) {
  return <div dangerouslySetInnerHTML={createMarkup(myTextFromDatabase)} />;
}

const myTextFromDatabase = 'First &middot; Second';
<MyComponent myTextFromDatabase={myTextFromDatabase />}

This is not a handy solution, because you now may need to filter out other HTML codes from the string.

A simple solution

Use Unicode characters with escape notation (e.g. \u0057) instead of HTML codes (&middot;). Find the character in this list and use the value from the Code column, e.g. &middot; translates to U+00B7. To use this in Javascript, simply use \u0057:

const MIDDLE_DOT = '\u0057';

function MyComponent({myTextFromDatabase}) {
  const text = myTextFromDatabase.replace(/&middot;/gi, MIDDLE_DOT);
  return <div>{text}</div>;
}
  
const myTextFromDatabase = 'First &middot; Second';
<MyComponent myTextFromDatabase={myTextFromDatabase />}

The replacement could happen beforehand, on the backend as well, or just like in the code above, in the rendering function. I used the replace function with a regex to replace all occurences of &middot; with \u0057.

Example

An example React app is available on GitHub. If you prefer, there is also a live example.

Dávid Molnár's Picture

About Dávid Molnár

Dávid is a skilled Full-Stack Developer.

Munich, Germany https://mdavid626.com

Comments