https://github.com/christo-pr/dangerously-set-html-content-v1
Render raw html on your own risk!
https://github.com/christo-pr/dangerously-set-html-content-v1
dangerouslysetinnerhtml innerhtml raw-html reactjs
Last synced: about 1 year ago
JSON representation
Render raw html on your own risk!
- Host: GitHub
- URL: https://github.com/christo-pr/dangerously-set-html-content-v1
- Owner: christo-pr
- Created: 2019-12-12T18:25:47.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2021-08-23T15:29:44.000Z (almost 5 years ago)
- Last Synced: 2024-10-27T21:48:47.767Z (over 1 year ago)
- Topics: dangerouslysetinnerhtml, innerhtml, raw-html, reactjs
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/dangerously-set-html-content
- Size: 353 KB
- Stars: 56
- Watchers: 2
- Forks: 8
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
- stars - christo-pr/dangerously-set-html-content-v1
README
⚠️⚠️⚠️
dangerously-set-html-content
⚠️⚠️⚠️
> Render raw html at your own risk!
[](https://www.npmjs.com/package/dangerously-set-html-content) [](https://standardjs.com)
## Context
Here's a blog post that explain more in detail:
- [Render dangerous content with React](https://dev.to/christo_pr/render-dangerous-content-with-react-2j7j)
## TL;DR
React uses `dangerouslySetInnerHtml` prop to render raw html, and works pretty much well for almost all the cases, but what if your html has some `scripts` tags inside??
When you use `dangerouslySetInnerHtml` on a component, internally react is using the `innerHtml` property of the node to set the content, which for [safety purposes](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations) doesn't execute any javascript.
This behavior seemed very odd to me (I mean the prop name contains the word `dangerously`, 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 the `document` has something called [Range](https://developer.mozilla.org/en-US/docs/Web/API/Range), this API let you create a fragment of the document, so using that I created `dangerously-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** 🚨🚨
## Install
```bash
yarn add dangerously-set-html-content
// or
// npm install --save dangerously-set-html-content
```
## Usage
```jsx
import React from 'react'
import InnerHTML from 'dangerously-set-html-content'
function Example {
const html = `
This wil be rendered
alert('testing')
`
return (
)
}
```
This will also work for scripts with the `src` attribute set it
## License
MIT © [christo-pr](https://github.com/christo-pr)