Skip to content

Commit 6a92efd

Browse files
committed
feat!: sanitize with DOMPurify by default and add a React Native entry
The default entry now sanitizes the parsed tree in place with a private DOMPurify instance, so what DOMPurify checked is exactly what renders. On top of DOMPurify's defaults it only removes what reaches past the fragment: <style> and <title>, form/formaction, position: fixed styles and javascript: attribute values. A new `purify` option merges a DOMPurify config over the built-in one, and DOMPurify still runs after a caller's own `sanitize`. A new `react-html5-parser/core` entry keeps the unsanitized parser at about 3 kB, and `react-html5-parser/native` renders HTML to React Native View, Text and Image components. It parses with htmlparser2, bundled into the entry so Metro versions that ignore package exports can resolve it, opens links only for http, https, mailto and tel, and loads images only from http, https and raster data URIs. The parser was audited against React 18 and 19: SVG attributes are mapped by default, form fields stay uncontrolled, React 19 head hoisting and <html>/<body> binding are avoided, and custom elements keep their attribute names. BREAKING CHANGE: react >= 18 is now required (react-native >= 0.71 for the native entry). `parse` from the default entry sanitizes, which grows it to about 15 kB; import from `react-html5-parser/core` to opt out. Entries in `components` render as React components rather than being called as functions, so an inline arrow function remounts its subtree on every render.
1 parent dfeac41 commit 6a92efd

28 files changed

Lines changed: 3743 additions & 1862 deletions

‎README.md‎

Lines changed: 122 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
# react-html5-parser
22

3-
Fast, simple and small (2kb) HTML to React parser in browser
4-
5-
### Work still in progress
3+
Fast, simple and small HTML to React parser for the browser and React Native, sanitized by default
64

75
## Install
86

@@ -12,12 +10,19 @@ npm install react-html5-parser
1210
yarn add react-html5-parser
1311
```
1412

13+
Requires React 18 or newer (`react >= 18`). The native entry also needs React Native 0.71 or newer.
14+
1515
## Use
1616

17-
## To read
17+
Three entry points:
1818

19-
- parse only html attributes (1.1kb) (default)
20-
- parse html and svg attributes (2kb) (need to update [attrsMap](#attrsMap) option)
19+
| Import | Target | Sanitizer | Size (min + gzip) |
20+
| --------------------------- | ------------ | ----------------------------------- | ----------------- |
21+
| `react-html5-parser` | browser | DOMPurify, on by default | 15.1 kB |
22+
| `react-html5-parser/core` | browser | none, bring your own via `sanitize` | 3 kB |
23+
| `react-html5-parser/native` | React Native | built-in allowlist (see below) | 26.5 kB |
24+
25+
The browser entries map HTML and SVG attributes to React props.
2126

2227
```ts
2328
import { parse } from "react-html5-parser";
@@ -39,32 +44,70 @@ parse("Lorem <div>ipsum</div>");
3944

4045
- `html`: The HTML string
4146
- `options` (`object?`): Options
42-
- `sanitize` (`function?`): Sanitize HTML string
43-
- `components` (`object?`): Override React elements. The keys are HTML equivalents (such as `div`)
47+
- `purify` (`object?`): DOMPurify config for the default entry, see below
48+
- `sanitize` (`function?`): Transform or sanitize the HTML string before parsing. On the default entry DOMPurify still runs after it
49+
- `components` (`object?`): Override React elements. The keys are lowercase HTML tag names (such as `div`). Each value is rendered as a React component, so it may use hooks
4450
- `mapNode` (`function?`): Override Dom node
45-
- `mapElement` (`function?`): Override React element. Сalled after `components` override
51+
- `mapElement` (`function?`): Override React element. Called after `components` override; for an overridden tag it receives the component element (`element.type` is the component)
4652
- `attrsMap` (`object?`): Map for converting dom attributes to react attributes
4753
- `onError` (`function?`): Listen errors, if we provide not a string `html` or catch an unexpected internal error
4854

4955
#### Return
5056

5157
Return `React.Fragment | null`. We get `null` if html is not a string or catch an unexpected internal error
5258

53-
### sanitize `(html: string) => string`
59+
### Built-in sanitizer
60+
61+
`parse` from `react-html5-parser` sanitizes with [DOMPurify](https://github.com/cure53/DOMPurify). It runs on the parsed DOM tree in place, not on a string, so the tree DOMPurify checked is exactly the tree that gets rendered: no second parse and no mutation XSS. It uses a private DOMPurify instance, so an app's own DOMPurify setup and hooks are not affected.
62+
63+
On top of DOMPurify's defaults (no scripts, event handlers, `javascript:` URLs, frames, embeds or DOM clobbering ids), it removes only what reaches past the parsed fragment:
64+
65+
- `<style>` and `<title>`, which act on the whole page;
66+
- `form` and `formaction`, which submit the page's own form to another site;
67+
- a `style` attribute that sets `position: fixed`, which can lay content over the whole page;
68+
- any attribute whose value is a `javascript:` URL.
69+
70+
It keeps `target` on links and sets `rel="noopener noreferrer"` with it. DOMPurify's allowlist still drops attributes such as `contenteditable` and `fetchpriority`.
71+
72+
Unknown and custom elements are removed and their content is kept, except tags you map in `components`: those are allowed. A mapped custom element (`x-card`) also keeps its custom attributes as props, without event handlers or `javascript:` values.
73+
74+
Limits worth knowing:
75+
76+
- CSS can still move content outside its box (`position: absolute`, negative margins, transforms). Put `contain: paint` on the element that holds the parsed HTML to clip it.
77+
- Attributes such as `popovertarget` and `commandfor` stay, and can open the page's own popovers and dialogs by id. Forbid them through `purify` if that matters.
78+
- An `id` such as `APP_CONFIG` still becomes `window.APP_CONFIG` when the page defines no global of that name. Do not read optional globals from `window` on pages that render user HTML.
79+
80+
### purify `DOMPurify.Config`
81+
82+
Default entry only. Merged over the built-in config, so each key you pass replaces the built-in one; `ADD_TAGS` is combined with the tags mapped in `components`.
5483

5584
```ts
5685
import { parse } from "react-html5-parser";
57-
import dompurify from "dompurify";
5886

59-
// trim string
60-
parse("<div>Lorem ipsum</div>", { sanitize: (html: string) => html.trim() });
87+
parse(html, {
88+
purify: {
89+
ADD_ATTR: ["contenteditable"],
90+
FORBID_ATTR: ["form", "formaction", "popovertarget", "commandfor"],
91+
},
92+
});
93+
```
94+
95+
The tree is always sanitized in place, so `IN_PLACE`, `RETURN_DOM`, `RETURN_DOM_FRAGMENT`, `RETURN_TRUSTED_TYPE` and `WHOLE_DOCUMENT` are ignored. The `position: fixed`, `javascript:` and `rel="noopener"` checks run whatever the config says.
96+
97+
### sanitize `(html: string) => string`
98+
99+
```ts
100+
import { parse } from "react-html5-parser/core";
101+
import dompurify from "dompurify";
61102

62-
// sanitize with dompurify
103+
// your own DOMPurify setup on the core entry
63104
parse("<div>Lorem ipsum</div>", {
64105
sanitize: (html: string) => dompurify.sanitize(html),
65106
});
66107
```
67108

109+
On the default entry, DOMPurify runs after your `sanitize`, so a function that only trims or rewrites the HTML never turns sanitizing off. Use the core entry to replace DOMPurify.
110+
68111
### components `{ [key: string]: (props: {}) => ReactNode }`
69112

70113
```tsx
@@ -91,26 +134,26 @@ JSX
91134
</>
92135
```
93136

94-
### mapNode `(node: Node, key: number | string, options = {}) => Node | ReactNode }`
137+
### mapNode `(node: Node, key: number | string, options = {}) => Node | ReactNode`
95138

96139
```ts
97140
import { parse, renderNode, renderNodes } from "react-html5-parser";
98141

99142
parse("<div>Lorem <b>ipsum</b></div>", {
100143
mapNode: (node: Node, key: string | number, options = {}) => {
101-
// return renderNode(node); // render node as react node
102-
// return renderNodes(node.childNodes); // render only childNodes
144+
// return renderNode(node, key, options); // render node as react node
145+
// return renderNodes(node.childNodes, options); // render only childNodes
103146

104147
return node;
105148
},
106149
});
107150
```
108151

109-
### mapElement `(element: ReactElement, options = {}) => ReactNode }`
152+
### mapElement `(element: ReactElement) => ReactNode`
110153

111154
```ts
112155
parse("<div>Lorem <b>ipsum</b></div>", {
113-
mapElement: (element: ReactElement, options = {}) => {
156+
mapElement: (element: ReactElement) => {
114157
if (element.type === "p") {
115158
return <element.type {...element.props} />;
116159
}
@@ -122,17 +165,14 @@ parse("<div>Lorem <b>ipsum</b></div>", {
122165

123166
### attrsMap `{ [key: string]: string }`
124167

125-
```ts
126-
import { parse, parseAttrs, SVG_ATTRIBUTES } from "react-html5-parser";
168+
HTML and SVG attributes are mapped by default. `attrsMap` adds to or overrides that mapping.
127169

128-
// need for the correct parsing svg attributes
129-
const svgAttrsMap = parseAttrs(SVG_ATTRIBUTES);
170+
```ts
171+
import { parse } from "react-html5-parser";
130172

131173
// map custom attrs, convert classname to class
132-
const customMap = { classname: "class" };
133-
134-
parse("<div>Lorem <b>ipsum</b></div>", {
135-
attrsMap: { ...svgAttrsMap, ...customMap },
174+
parse("<div classname='a'>Lorem <b>ipsum</b></div>", {
175+
attrsMap: { classname: "className" },
136176
});
137177
```
138178

@@ -148,3 +188,58 @@ const res: null = parse(undefined, {
148188
},
149189
});
150190
```
191+
192+
## React Native
193+
194+
```tsx
195+
import { parse } from "react-html5-parser/native";
196+
197+
function Article({ html }: { html: string }) {
198+
return <View>{parse(html, { textStyle: { fontSize: 16 } })}</View>;
199+
}
200+
```
201+
202+
React Native has no DOM, so this entry parses with [htmlparser2](https://github.com/fb55/htmlparser2), bundled into the entry so it also works with Metro versions that ignore package `exports`. Tags become native components:
203+
204+
- Block tags (`p`, `div`, `h1`–`h6`, `blockquote`, `pre`, `ul`, `ol`, `li`, `table`, `tr`, `td`, `hr`, …) become `View`. Their text is wrapped in `Text`, since React Native throws on a string directly inside a `View`.
205+
- Inline tags (`b`, `strong`, `i`, `em`, `u`, `s`, `code`, `span`, `a`, …) become nested `Text`. A block inside inline content becomes `Text` too, on a line of its own.
206+
- `img` becomes `Image`. Give it `width` and `height` in pixels: without both it takes the full width at a 16:9 ratio. Inside text, such as in a link, React Native shows an image only with both set.
207+
- `br` becomes a line break. Whitespace collapses as in HTML, except inside `pre`.
208+
- Unknown tags render only their content.
209+
210+
Options: `components`, `mapElement`, `sanitize` and `onError` work as on the web, plus:
211+
212+
- `tagStyles` (`{ [tag]: { view?, text?, image? } }`): merged over the default style of each tag.
213+
- `textStyle`: the base style of all text.
214+
- `onLinkPress` (`(href: string) => void`): handles every link tap, relative links included. You are responsible for checking the URL.
215+
216+
`components` receives the tag's attributes as props, except `style` (CSS text, which React Native rejects), `key`, `ref` and `children`, and the rendered children.
217+
218+
There is no script engine, so the native sanitizer guards what React Native can reach:
219+
220+
- links open through `Linking` only for `http:`, `https:`, `mailto:` and `tel:`; any other scheme, including app schemes and `intent:`, renders as plain text;
221+
- images load only from `http:`, `https:` and base64 PNG, JPEG, GIF or WebP data URIs;
222+
- `script`, `style`, `iframe`, `object`, `embed`, `svg`, `math`, `video`, `audio`, form controls and `head` content are dropped, as is any element with `hidden`;
223+
- `style` attributes are ignored, so injected markup cannot overlay the app.
224+
225+
Remote images still reveal the reader's IP address to the image host. Map `img` in `components` to block or proxy them.
226+
227+
## Errors
228+
229+
`parse` never throws for bad input. It returns `null` and calls `onError(error, html)` when:
230+
231+
- `html`, or the result of `sanitize`, is not a string (`TypeError`);
232+
- `sanitize`, `mapNode` or `mapElement` throws;
233+
- there is no DOM, e.g. on the server (`ReferenceError`);
234+
- the HTML nests deeper than the call stack allows (`RangeError`; browsers cap parser depth at about 512, so this only shows up outside them).
235+
236+
An error thrown inside `onError` reaches the caller. A component from `components` renders later, inside React, so its errors go to the nearest error boundary, not to `onError`.
237+
238+
## Notes
239+
240+
- HTML is parsed inside a `<template>` element, so scripts never run and images never load while parsing.
241+
- `key`, `ref` and `children` attributes are ignored, since React would read them as its own props.
242+
- Form fields stay uncontrolled: `value` / `checked` on `<input>`, the text of a `<textarea>` and the `selected` options of a `<select>` become `defaultValue` / `defaultChecked`. A file input's `value` is dropped, since React throws on it.
243+
- `<noscript>` content is parsed as text, as browsers do while scripting is enabled.
244+
- `hidden="until-found"` becomes plain `hidden`: React 19 treats `hidden` as a boolean.
245+
- In the core entry, `async` is dropped from `<script>`, so React 19 renders it inert instead of hoisting and running it, and `<title>`, `<meta>` and `<link>` are hoisted into the document `<head>` by React 19.

‎__tests__/attributes.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ function filterAttrs(
2525
}, {});
2626
}
2727

28-
function attrsObjToNode(attrs: Record<string, any>): any {
28+
function attrsObjToNode(attrs: Record<string, any>, localName = "input"): any {
2929
const attributes = Object.entries(attrs).reduce<Attr[]>(
3030
(acc, [nodeName, nodeValue]) => (
3131
acc.push({ nodeName, nodeValue } as Attr), acc
@@ -34,6 +34,7 @@ function attrsObjToNode(attrs: Record<string, any>): any {
3434
);
3535

3636
return {
37+
localName,
3738
attributes,
3839
getAttribute: (name: string) => attrs[name],
3940
};

‎__tests__/errors.test.tsx‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import React from "react";
2+
import { parse } from "../src";
3+
4+
describe("parse error handling", () => {
5+
it.each([
6+
["undefined", undefined],
7+
["null", null],
8+
["a number", 1],
9+
["an object", {}],
10+
["an array", ["<p>x</p>"]],
11+
])("returns null and reports a TypeError for %s", (_, html) => {
12+
const onError = jest.fn();
13+
14+
// @ts-expect-error non-string input from untyped callers
15+
expect(parse(html, { onError })).toBeNull();
16+
expect(onError).toHaveBeenCalledWith(
17+
new TypeError("HTML must be a string"),
18+
html
19+
);
20+
});
21+
22+
it("returns null without throwing when no onError is given", () => {
23+
// @ts-expect-error non-string input from untyped callers
24+
expect(parse(undefined)).toBeNull();
25+
});
26+
27+
it("reports an error thrown by sanitize", () => {
28+
const error = new Error("sanitize failed");
29+
const onError = jest.fn();
30+
31+
const node = parse("<p>x</p>", {
32+
sanitize: () => {
33+
throw error;
34+
},
35+
onError,
36+
});
37+
38+
expect(node).toBeNull();
39+
expect(onError).toHaveBeenCalledWith(error, "<p>x</p>");
40+
});
41+
42+
it("reports a sanitize result that is not a string", () => {
43+
const onError = jest.fn();
44+
45+
// @ts-expect-error sanitize returning a non-string
46+
parse("<p>x</p>", { sanitize: () => undefined, onError });
47+
48+
expect(onError).toHaveBeenCalledWith(
49+
new TypeError("Sanitized HTML must be a string"),
50+
undefined
51+
);
52+
});
53+
54+
it.each([
55+
[
56+
"mapNode",
57+
{
58+
mapNode: () => {
59+
throw new Error("boom");
60+
},
61+
},
62+
],
63+
[
64+
"mapElement",
65+
{
66+
mapElement: () => {
67+
throw new Error("boom");
68+
},
69+
},
70+
],
71+
])("reports an error thrown by %s", (_, options) => {
72+
const onError = jest.fn();
73+
74+
expect(parse("<p>x</p>", { ...options, onError })).toBeNull();
75+
expect(onError).toHaveBeenCalledWith(new Error("boom"), "<p>x</p>");
76+
});
77+
78+
it("lets an error rethrown from onError reach the caller", () => {
79+
expect(() =>
80+
// @ts-expect-error non-string input from untyped callers
81+
parse(null, {
82+
onError: (error) => {
83+
throw error;
84+
},
85+
})
86+
).toThrow(TypeError);
87+
});
88+
89+
it("reports nesting too deep for the call stack instead of throwing", () => {
90+
const onError = jest.fn();
91+
92+
expect(parse("<div>".repeat(20000), { onError })).toBeNull();
93+
expect(onError).toHaveBeenCalledWith(
94+
expect.objectContaining({ name: "RangeError" }),
95+
expect.any(String)
96+
);
97+
});
98+
99+
it("ignores an onError that is not a function", () => {
100+
// @ts-expect-error onError of the wrong type from untyped callers
101+
expect(parse(null, { onError: "nope" })).toBeNull();
102+
});
103+
it("treats null options as no options", () => {
104+
expect(parse("<p>x</p>", null)).not.toBeNull();
105+
});
106+
});

‎__tests__/index.test.tsx‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,6 @@ describe("parse", () => {
5757
});
5858

5959
it("should parse components", () => {
60-
global.DOMParser = jest.fn().mockImplementationOnce(() => {});
61-
6260
const node = parse(
6361
`Hello,<c>!</c><div class='active' style='color: red; font-size-adjust: initial; font-weight: 600' id>, world<span style>!</span><b></b></div><input type='text' value="Submit">`,
6462
{

0 commit comments

Comments
 (0)