Reputation: 1102
In React, I need to take a JavaScript String
and display it as HTML. I am using dangerouslySetInnerHTML
to accomplish this, but I want to do this more safely by only allowing specific tags (e.g. ul
and li
). How can I accomplish this?
In the code below, I only want to allow the ul
and li
tags.
<p
dangerouslySetInnerHTML={{
__html: '<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>'
}}></p>
When I try using sanitizeHtml
, I get this:
./node_modules/sanitize-html/node_modules/postcss/lib/lazy-result.js
Module parse failed: Unexpected token (143:21)
You may need an appropriate loader to handle this file type.
Upvotes: 2
Views: 2963
Reputation: 4934
There is an open source library called sanitize-html that does exactly what you want. From their examples:
// Allow only a super restricted set of tags and attributes
const clean = sanitizeHtml(dirty, {
allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],
allowedAttributes: {
'a': [ 'href' ]
},
allowedIframeHostnames: ['www.youtube.com']
});
Upvotes: 3