Skip to content

mdavid626/react-html-entities-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

How to run the example

Run npm install and then npm start.

Live example

A live example is available on https://mdavid626.github.io/react-html-entities-example/.

References

Based on this blog post from Dávid Molnár.

About

This is an example for showing how to render HTML entities in a React app without using dangerouslySetInnerHTML

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published