I've got some user generated html markup from a text area and I'd like to render it on another part of the screen. The markup is saved as a string in the props of the component.
I don't want to use dangerouslysethtml for obvious reasons. Is there a parser such as marked but for html so that it strips out script tags and other invalid html.
React's goal is in many ways to render HTML in a web page. React renders HTML to the web page by using a function called ReactDOM. render() .
The React documentation does a good job of explaining why you'd want to sanitize data that gets passed in as HTML, but as far as I can tell it leaves you on your own to figure out how exactly to do that sanitation.
The npm package react-html-parser was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use.
Fetching the HTML from an external source One simple way to do dynamically fetch a choose a specific file would be to let your backend (e.g php) read the file from a local folder, parse the text, and send it back through an AJAX request.
Sanitize the html using the sanitize-html module, and render the sanitized string using dangerouslySetInnerHTML.
You can create a simple wrapper component:
const defaultOptions = { allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ], allowedAttributes: { 'a': [ 'href' ] }, allowedIframeHostnames: ['www.youtube.com'] }; const sanitize = (dirty, options) => ({ __html: sanitizeHtml( dirty, options: { ...defaultOptions, ...options } ) }); const SanitizeHTML = ({ html, options }) => ( <div dangerouslySetInnerHTML={sanitize(html, options)} /> );
Usage:
<SanitizeHTML html="<img src=x onerror=alert('img') />" />
You can also use react-sanitized-html's SanitizedHTML component, which is a react wrapper around sanitize-html
:
<SanitizedHTML allowedAttributes={{ 'a': ['href'] }} allowedTags={['a']} html={ `<a href="http://bing.com/">Bing</a>` } />
An example based on the accepted answer:
import sanitizeHtml from 'sanitize-html'; const MyComponent = () => { dirty = '<a href="my-slug" target="_blank" onClick="evil()">click</a>'; const clean = sanitizeHtml(dirty, { allowedTags: ['b', 'i', 'em', 'strong', 'a'], allowedAttributes: { a: ['href', 'target'] } }); return ( <div dangerouslySetInnerHTML={{__html: clean}} /> ); };
MyComponent
renders div
containing the link without onClick="evil()"
:
<a href="my-slug" target="_blank">click</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With