HTML to React parser.
npm install html-react-parser






HTML to React parser that works on both the server (Node.js) and the client (browser):
```
HTMLReactParser(string[, options])
The parser converts an HTML string to one or more React elements.
To replace an element with another element, check out the replace option.
#### Example
`ts
import parse from 'html-react-parser';
parse('
Hello, World!
'); // React.createElement('p', {}, 'Hello, World!')StackBlitz | TypeScript | JSFiddle | Examples
Table of Contents
- Install
- Usage
- replace
- replace with TypeScript
- replace element and children
- replace element attributes
- replace and remove element
- transform
- library
- htmlparser2
- trim
- Migration
- v5
- v4
- v3
- v2
- v1
- FAQ
- Is this XSS safe?
- Does invalid HTML get sanitized?
- Are
Usage
Import ES module:
`ts
import parse from 'html-react-parser';
`Or require CommonJS module:
`ts
const parse = require('html-react-parser').default;
`Parse single element:
`ts
parse('single
');
`Parse multiple elements:
`ts
parse('Item 1 Item 2 ');
`Make sure to render parsed adjacent elements under a parent element:
`tsx
{parse(
)}
`Parse nested elements:
`ts
parse('Lorem ipsum
');
`Parse element with attributes:
`ts
parse(
'
',
);
`$3
The
replace option allows you to replace an element with another element.The
replace callback's first argument is domhandler's node:`ts
parse('
', {
replace(domNode) {
console.dir(domNode, { depth: null });
},
});
`
Console output
`ts
Element {
type: 'tag',
parent: null,
prev: null,
next: null,
startIndex: null,
endIndex: null,
children: [],
name: 'br',
attribs: {}
}
`
The element is replaced if a valid React element is returned:
`tsx
parse('text
', {
replace(domNode) {
if (domNode.attribs && domNode.attribs.id === 'replace') {
return replaced;
}
},
});
`The second argument is the index:
`ts
parse('
', {
replace(domNode, index) {
console.assert(typeof index === 'number');
},
});
`> [!NOTE]
>
> The index will restart at 0 when traversing the node's children so don't rely on index being a unique key. See #1259.
#### replace with TypeScript
You need to check that
domNode is an instance of domhandler's Element:`tsx
import { HTMLReactParserOptions, Element } from 'html-react-parser';const options: HTMLReactParserOptions = {
replace(domNode) {
if (domNode instanceof Element && domNode.attribs) {
// ...
}
},
};
`Or use a type assertion:
`tsx
import { HTMLReactParserOptions, Element } from 'html-react-parser';const options: HTMLReactParserOptions = {
replace(domNode) {
if ((domNode as Element).attribs) {
// ...
}
},
};
`If you're having issues, take a look at our Create React App example.
#### replace element and children
Replace the element and its children (see demo):
`tsx
import parse, { domToReact } from 'html-react-parser';const html =
keep me and make me pretty!
;const options = {
replace({ attribs, children }) {
if (!attribs) {
return;
}
if (attribs.id === 'main') {
return
{domToReact(children, options)}
;
} if (attribs.class === 'prettify') {
return (
{domToReact(children, options)}
);
}
},
};
parse(html, options);
`
HTML output
`html
keep me and make me pretty!
`
#### replace element attributes
Convert DOM attributes to React props with
attributesToProps:`tsx
import parse, { attributesToProps } from 'html-react-parser';const html =
;const options = {
replace(domNode) {
if (domNode.attribs && domNode.name === 'main') {
const props = attributesToProps(domNode.attribs);
return
;
}
},
};parse(html, options);
`
HTML output
`html
`
#### replace and remove element
Exclude an element from rendering by replacing it with
:`tsx
parse('
', {
replace: ({ attribs }) => attribs?.id === 'remove' && <>>,
});
`
HTML output
`html
`
$3
The
transform option allows you to transform each element individually after it's parsed.The
transform callback's first argument is the React element:`tsx
parse('
', {
transform(reactNode, domNode, index) {
// this will wrap every element in a div
return {reactNode};
},
});
`$3
The
library option specifies the UI library. The default library is React.To use Preact:
`ts
parse('
', {
library: require('preact'),
});
`Or a custom library:
`ts
parse('
', {
library: {
cloneElement: () => {
/ ... /
},
createElement: () => {
/ ... /
},
isValidElement: () => {
/ ... /
},
},
});
`$3
> [!WARNING]
>
>
htmlparser2 options _do not work on the client-side_ (browser); they _only work on the server-side_ (Node.js). By overriding the options, it can break universal rendering.Default htmlparser2 options can be overridden in >=0.12.0.
xmlMode:`ts
parse('', {
htmlparser2: {
xmlMode: true,
},
});
`$3
By default, whitespace is preserved:
`ts
parse('
\n'); // [React.createElement('br'), '\n']
`But certain elements like
To remove whitespace, enable the
trim option:`ts
parse('
\n', { trim: true }); // React.createElement('br')
`However, intentional whitespace may be stripped out:
`ts
parse('
', { trim: true }); // React.createElement('p')
`Migration
$3
Migrated to TypeScript. CommonJS imports require the
.default key:`ts
const parse = require('html-react-parser').default;
`If you're getting the error:
`
Argument of type 'ChildNode[]' is not assignable to parameter of type 'DOMNode[]'.
`Then use type assertion:
`ts
domToReact(domNode.children as DOMNode[], options);
`See #1126.
$3
htmlparser2 has been upgraded to v9.
$3
domhandler has been upgraded to v5 so some parser options like
normalizeWhitespace have been removed.Also, it's recommended to upgrade to the latest version of TypeScript.
$3
Since v2.0.0, Internet Explorer (IE) is no longer supported.
$3
TypeScript projects will need to update the types in v1.0.0.
For the
replace option, you may need to do the following:`tsx
import { Element } from 'domhandler/lib/node';parse('
', {
replace(domNode) {
if (domNode instanceof Element && domNode.attribs.class === 'remove') {
return <>>;
}
},
});
`Since v1.1.1, Internet Explorer 9 (IE9) is no longer supported.
FAQ
$3
No, this library is _not_ XSS (cross-site scripting) safe. See #94.
$3
No, this library does _not_ sanitize HTML. See #124, #125, and #141.
$3
Although