In this article, I’ll explain how you can inject HTML into a React component without using dangerouslySetInnerHTML
it as it’s not safe to use. It can cause cross-site scripting (XSS) attacks.
React documentation says:
dangerouslySetInnerHTML
is React’s replacement for usinginnerHTML
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:![]()
But the issue is that
srcdoc
has very limited browser support. It isn’t supported in IE and Edge. There is a polyfill available but it isn’t useful in this case because it requiresallow-scripts
, which is not safe.Why not Use
iframe.document.open()/write()/close()?
Let’s write our own custom Iframe!
It’s not that simple as using
srcdoc
but it’s nevertheless safe to use and works in every browser:Usage
Simple isn’t it?
Did you learn something new today? Comments and feedback always make the writer happy!