- Notifications
You must be signed in to change notification settings - Fork8
Render raw html on your own risk!
christo-pr/dangerously-set-html-content-v1
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Render raw html at your own risk!
Here's a blog post that explain more in detail:
React usesdangerouslySetInnerHtml
prop to render raw html, and works pretty much well for almost all the cases, but what if your html has somescripts
tags inside??
When you usedangerouslySetInnerHtml
on a component, internally react is using theinnerHtml
property of the node to set the content, which forsafety purposes doesn't execute any javascript.
This behavior seemed very odd to me (I mean the prop name contains the worddangerously
, and also you need to pass an object with a__html
propery, which is on purpose, so you really know what you doing), although has totally sense now, still doesn't solve my issue
After a little bit of search I found that thedocument
has something calledRange, this API let you create a fragment of the document, so using that I createddangerously-set-html-content
.
This React component renders html from a string, with the plus of executing all the js code that html contains!! 🎉
🚨🚨USE IT AT YOUR OWN RISK 🚨🚨
yarn add dangerously-set-html-content// or// npm install --save dangerously-set-html-content
importReactfrom'react'importInnerHTMLfrom'dangerously-set-html-content'functionExample{consthtml=` <div>This wil be rendered</div> <script> alert('testing') </script> `return(<InnerHTMLhtml={html}/>)}
This will also work for scripts with thesrc
attribute set it
MIT ©christo-pr
About
Render raw html on your own risk!
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.