Skip to content

Instantly share code, notes, and snippets.

@blobaugh
Created December 5, 2024 17:22
Show Gist options
  • Save blobaugh/3cbb8e1038c0a607c2427d79535c7a51 to your computer and use it in GitHub Desktop.
Save blobaugh/3cbb8e1038c0a607c2427d79535c7a51 to your computer and use it in GitHub Desktop.
Utility helper to escape output in React, that uses the same sanitation as wp_kses
import sanitizeHtml from "sanitize-html";
export const escapeHtml = (unsafeHtml) => {
const allowedTags = [
"a", "abbr", "acronym", "b", "blockquote", "cite", "code", "del", "em",
"i", "q", "strike", "strong", "ul", "ol", "li", "br", "p", "span", "div",
"img", "h1", "h2", "h3", "h4", "h5", "h6", "table", "thead", "tbody",
"tfoot", "tr", "th", "td", "pre"
];
const allowedAttributes = {
a: ["href", "title", "rel", "target"],
abbr: ["title"],
acronym: ["title"],
blockquote: ["cite"],
q: ["cite"],
img: ["src", "alt", "title", "width", "height"],
div: ["class", "id", "style"],
span: ["class", "id", "style"],
table: ["class", "id", "style", "border"],
th: ["class", "id", "style", "colspan", "rowspan"],
td: ["class", "id", "style", "colspan", "rowspan"],
p: ["class", "id", "style"],
};
return sanitizeHtml(unsafeHtml, {
allowedTags,
allowedAttributes,
parser: {
decodeEntities: true
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment