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:
dangerouslySetInnerHTMLis React’s replacement for using
innerHTMLin 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.
dangerouslySetInnerHTMLis quite simple:
But the issue is that
srcdochas 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 requires
allow-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
srcdocbut it’s nevertheless safe to use and works in every browser:
Simple isn’t it?
Did you learn something new today? Comments and feedback always make the writer happy!