@wordpress/block-library
Version:
Block library for the WordPress editor.
42 lines (41 loc) • 1.49 kB
JavaScript
import clsx from "clsx";
import parse, { attributesToProps, domToReact } from "html-react-parser";
import { safeHTML } from "@wordpress/dom";
import { jsx } from "react/jsx-runtime";
// packages/block-library/src/utils/html-renderer.jsx
/**
* Renders HTML content as React elements with optional wrapper props.
*
* @param {Object} props - The props for the component.
* @param {Object} props.wrapperProps - The props to merge with the root element.
* className and style are merged with the parsed HTML attributes.
* @param {string} props.html - The HTML content to render.
* @return {React.JSX.Element} The rendered React elements.
*/
const HtmlRenderer = ({ wrapperProps = {}, html = "" }) => {
const options = { replace: ({ name, type, attribs, parent, children }) => {
if (type === "tag" && name) {
const parsedProps = attributesToProps(attribs || {});
const TagName = name;
if (!parent) {
const mergedProps = {
...parsedProps,
...wrapperProps,
className: clsx(parsedProps.className, wrapperProps.className),
style: {
...parsedProps.style || {},
...wrapperProps.style || {}
}
};
return /* @__PURE__ */ jsx(TagName, {
...mergedProps,
children: domToReact(children, options)
});
}
}
} };
const sanitizedContent = safeHTML(html);
return parse(sanitizedContent, options);
};
export { HtmlRenderer as default };
//# sourceMappingURL=html-renderer.mjs.map