Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 1,000,000+ packages pre-installed, including dangerously-set-html-content with all npm packages installed. Try it out:

require("prop-types/package.json"); // prop-types is a peer dependency. require("react/package.json"); // react is a peer dependency. require("react-dom/package.json"); // react-dom is a peer dependency. var dangerouslySetHtmlContent = require("dangerously-set-html-content")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

dangerously-set-html-content v1.0.8

Render raw html at your own risk!

⚠️⚠️⚠️ dangerously-set-html-content ⚠️⚠️⚠️

Render raw html at your own risk!

NPM JavaScript Style Guide

Context

Here's a blog post that explain more in detail:

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 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, 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

yarn add dangerously-set-html-content
// or
// npm install --save dangerously-set-html-content

Usage

import React from 'react'

import InnerHTML from 'dangerously-set-html-content'

function Example {

  const html = `
    <div>This wil be rendered</div>
    <script>
      alert('testing')
    </script>

  `

  return (
    <InnerHTML html={html} />
  )
}

This will also work for scripts with the src attribute set it

License

MIT © christo-pr

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free