If you want know how to safely render html in react? Sanitize the html using the sanitize-html module, and render the sanitized string using dangerouslySetInnerHTML.
You can create a simple wrapper component:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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:
1 |
<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:
1 2 3 4 5 |
<SanitizedHTML allowedAttributes={{ 'a': ['href'] }} allowedTags={['a']} html={ `<a href="http://bing.com/">Bing</a>` } /> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.