Skip to content

Instantly share code, notes, and snippets.

@timbryandev
Created August 11, 2022 13:59
Show Gist options
  • Save timbryandev/be333579506ff53d552aa13781d9dbb7 to your computer and use it in GitHub Desktop.
Save timbryandev/be333579506ff53d552aa13781d9dbb7 to your computer and use it in GitHub Desktop.
Prevent XSS in React via dangerouslySetInnerHTML
/*
Exampmes:
// 1
const markup = `<p>Hola <img src='none.png' onerror='alert("Rainbow mode FTW!")'> Sharon</p>`
<DangerousHtml innerHTML={markup} /> // <p>Hola <img src='none.png'> Sharon</p>
// 2
<DangerousHtml
content={`<p>
Hi
<script src="https://example.com/malicious-tracking"></script>
Fiona, here is the link to enter your bank details:
<iframe src="https://example.com/defo-not-the-actual-bank"></iframe>
</p>`}
/>
// Notes
* Remember to include or install https://github.com/cure53/DOMPurify
*/
import React from 'react'
import DOMPurify from 'dompurify'
const sanitize = dirty => DOMPurify.sanitize(dirty)
const DangerousHtml = ({ innerHTML, tag }) => {
const clean = sanitize(innerHTML)
if (typeof Tag === 'undefined') {
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
return <tag dangerouslySetInnerHTML={{ __html: clean }} />
}
export default DangerousHtml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment