React app rendering html entities such as ampersand as escaped

时光毁灭记忆、已成空白 提交于 2019-12-05 04:51:29

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!