Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions __tests__/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,38 @@ describe('replace option', () => {
expect(checks).toEqual([true, true, true]);
});

it('provides text and comment nodes that are instances of the exported classes', () => {
const checks: boolean[] = [];

parse('Hello <strong>world</strong><!--note-->', {
replace(domNode) {
if (
domNode instanceof HTMLReactParser.Text &&
domNode.data === 'Hello '
) {
checks.push(true);
}

if (
domNode instanceof HTMLReactParser.Element &&
domNode.name === 'strong'
) {
const [text] = domNode.children;
checks.push(text instanceof HTMLReactParser.Text);
}

if (
domNode instanceof HTMLReactParser.Comment &&
domNode.data === 'note'
) {
checks.push(true);
}
},
});

expect(checks).toEqual([true, true, true]);
});

it('replaces the element if a valid React element is returned', () => {
expect(
parse(html.complex, {
Expand Down
26 changes: 18 additions & 8 deletions src/dom-to-react.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
/* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */

import { Element as DomHandlerElement } from 'domhandler';
import {
Comment as DomHandlerComment,
Element as DomHandlerElement,
Text as DomHandlerText,
} from 'domhandler';
import type { DOMNode, Element, Text } from 'html-dom-parser';
import type { JSX } from 'react';
import { cloneElement, createElement, isValidElement } from 'react';
Expand Down Expand Up @@ -155,13 +159,19 @@ export default function domToReact(

function normalizeDOMNodes(nodes: DOMNode[]): void {
for (const node of nodes) {
if (
node.type === 'tag' ||
node.type === 'script' ||
node.type === 'style'
) {
Object.setPrototypeOf(node, DomHandlerElement.prototype);
normalizeDOMNodes(node.children as DOMNode[]);
switch (node.type) {
case 'tag':
case 'script':
case 'style':
Object.setPrototypeOf(node, DomHandlerElement.prototype);
normalizeDOMNodes(node.children as DOMNode[]);
break;
case 'text':
Object.setPrototypeOf(node, DomHandlerText.prototype);
break;
case 'comment':
Object.setPrototypeOf(node, DomHandlerComment.prototype);
break;
}
}
}
Expand Down
Loading