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
:
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 (·
). Find the character in this list and use the value from the Code column, e.g. ·
translates to U+00B7
. To use this in Javascript, simply use \u0057
:
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 ·
with \u0057
.
Example
An example React app is available on GitHub. If you prefer, there is also a live example.
Comments