Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React app rendering html entities such as ampersand as escaped

I have a React app embedded in Wordpress page. It pulls content from a JSON api and displays it in various areas.

My problem is that all of the text content that comes from the api displays as escaped charachters i.e & displays where an ampersand should be.

My wordpress page has <meta charSet="utf-8" /> which I would normally expect to convert this, but is having no effecton the React content. Is it because the rendering is done within React? In which case do I need to set React somehow to be using UTF-8?

like image 506
Steve Avatar asked Sep 23 '18 14:09

Steve


1 Answers

HTML (including entities) will be rendered as a string when being rendered as an expression:

{htmlString}

In order to parse HTML, there is dangerouslySetInnerHTML prop:

<span dangerouslySetInnerHTML={{__html: htmlString }} />

As the name says, it's unsafe and should be generally avoided. If a string comes from untrusted source or a source that could be exploited, malicious code can be rendered to a client.

The preferable way is to decode entities specifically, e.g. with html-entities:

import { Html5Entities } from 'html-entities';
const htmlEntities = new Html5Entities();

...

{htmlEntities.decode(htmlString)}

The problem could be avoided by not storing HTML entities in the first place if possible.

like image 161
Estus Flask Avatar answered Oct 08 '22 11:10

Estus Flask