Created
August 18, 2020 11:54
-
-
Save StanisLove/c8b1ec85e7e59cf5177342cc27dac2a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import removeHTMLTags from './removeHTMLTags'; | |
const safetySetInnerHTML = (text?: string) => { | |
if (!text) return null; | |
const allowedTags = ['div', 'p', 'li', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'] | |
.map((tag) => [`<${tag}>`, `</${tag}>`]) | |
.flat(); | |
const allowedTagsRegex = RegExp(`(${allowedTags.map((tag) => tag.replace('/', '\\/')).join('|')})`); | |
const safetyText = text | |
.split(allowedTagsRegex) | |
.map((substr) => (allowedTags.includes(substr) ? substr : removeHTMLTags(substr))).join(); | |
return React.createElement('div', { dangerouslySetInnerHTML: { __html: safetyText } }); | |
}; | |
export default safetySetInnerHTML; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment