Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Render raw html on your own risk!

NotificationsYou must be signed in to change notification settings

christo-pr/dangerously-set-html-content-v1

Repository files navigation

Render raw html at your own risk!

NPMJavaScript Style Guide

Context

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

TL;DR

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

Install

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

Usage

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

License

MIT ©christo-pr

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp