In this article, I’ll explain how you can inject HTML in a React component without using dangerouslySetInnerHTML
as it’s not safe to use. It can cause cross-site scripting (XSS) attacks.
React documentation says:
_dangerouslySetInnerHTML_
_ is React’s replacement for using_innerHTML_
in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack._
Using _dangerouslySetInnerHTML_
is quite simple:
<div dangerouslySetInnerHTML={{ __html: "<p>Hello world!</p>"}} />
The problem with this is that the HTML you are injecting can be malformed, it can have CSS/JavaScript that breaks your app, or even worse, JavaScript that steals data from your application.
#software-development #programming #react #javascript #security