Fast, simple and small (2kb) HTML to React parser in browser
npm install react-html5-parser
// or
yarn add react-html5-parser
- parse only html attributes (1.1kb) (default)
- parse html and svg attributes (2kb) (need to update attrsMap option)
import { parse } from "react-html5-parser";
// Parse element
parse("<div>Lorem ipsum</div>");
// return createElement(React.Fragment, {}, React.createElement("div", {}, "Lorem ipsum"))
// Parse element inside the string
parse("Lorem <div>ipsum</div>");
// return createElement(React.Fragment, {}, ["Lorem ", React.createElement("div", {}, "ipsum")])
html
: The HTML stringoptions
(object?
): Optionssanitize
(function?
): Sanitize HTML stringcomponents
(object?
): Override React elements. The keys are HTML equivalents (such asdiv
)mapNode
(function?
): Override Dom nodemapElement
(function?
): Override React element. Сalled aftercomponents
overrideattrsMap
(object?
): Map for converting dom attributes to react attributesonError
(function?
): Listen errors, if we provide not a stringhtml
or catch an unexpected internal error
Return React.Fragment | null
. We get null
if html is not a string or catch an unexpected internal error
import { parse } from "react-html5-parser";
import dompurify from "dompurify";
// trim string
parse("<div>Lorem ipsum</div>", { sanitize: (html: string) => html.trim() });
// sanitize with dompurify
parse("<div>Lorem ipsum</div>", {
sanitize: (html: string) => dompurify.sanitize(html),
});
function Typography(props) {
return <span {...props} />;
}
// replace div with paragraph, and b with Typography
parse("<div>Lorem <b>ipsum</b></div>", {
components: {
div: (props) => <p {...props} />,
b: Typography,
},
});
JSX
<>
<p>
Lorem <span>ipsum</span>
</p>
</>
import { parse, renderNode, renderNodes } from "react-html5-parser";
parse("<div>Lorem <b>ipsum</b></div>", {
mapNode: (node: Node, key: string | number, options = {}) => {
// return renderNode(node); // render node as react node
// return renderNodes(node.childNodes); // render only childNodes
return node;
},
});
parse("<div>Lorem <b>ipsum</b></div>", {
mapElement: (element: ReactElement, options = {}) => {
if (element.type === "p") {
return <element.type {...element.props} />;
}
return element;
},
});
import { parse, parseAttrs, SVG_ATTRIBUTES } from "react-html5-parser";
// need for the correct parsing svg attributes
const svgAttrsMap = parseAttrs(SVG_ATTRIBUTES);
// map custom attrs, convert classname to class
const customMap = { classname: "class" };
parse("<div>Lorem <b>ipsum</b></div>", {
attrsMap: { ...svgAttrsMap, ...customMap },
});
// if we provide incorrect html, or get internal error
const res: null = parse(undefined, {
onError: (error: unknown, html: unknown) => {
bugsnag.notify(error, (event) => {
event.addMetadata("htmlparser", { html });
});
},
});