Skip to content

Commit 889623e

Browse files
Skip HTML comments when converting DOM nodes to React
- Update `domToReact` to skip if node is not "tag" or "text" - This ensures that HTML comments are ignored - Add tests to verify that HTML comments are ignored by the parser
1 parent 9e22732 commit 889623e

File tree

4 files changed

+30
-1
lines changed

4 files changed

+30
-1
lines changed

lib/dom-to-react.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,10 @@ function domToReact(nodes) {
4848
// continue recursion of creating React elements
4949
children = domToReact(node.children, options);
5050
}
51+
52+
// skip all other cases (e.g., comment)
53+
} else {
54+
continue;
5155
}
5256

5357
// specify a `key` prop if returning an array

test/data.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"multiple": "<p>foo</p><p>bar</p>",
55
"complex": "<html><head><title>Title</title></head><body><header id=\"header\">Header</header><h1>Heading</h1><p>Paragraph</p><div class=\"class1 class2\">Some <em>text</em>.</div><script>alert();</script></body></html>",
66
"textarea": "<textarea>foo</textarea>",
7-
"script": "<script>alert(1 < 2);</script>"
7+
"script": "<script>alert(1 < 2);</script>",
8+
"comment": "<!-- comment -->"
89
}
910
}

test/dom-to-react.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,21 @@ describe('dom-to-react parser', function() {
6767
);
6868
});
6969

70+
it('skips HTML comments', function() {
71+
var html = [data.html.single, data.html.comment, data.html.single].join('');
72+
var reactElements = domToReact(htmlToDOM(html));
73+
reactElements.forEach(function(reactElement) {
74+
assert(React.isValidElement(reactElement));
75+
assert(reactElement.key);
76+
});
77+
assert.deepEqual(
78+
reactElements,
79+
[
80+
React.createElement('p', { key: 0 }, 'foo'),
81+
// comment is in the middle
82+
React.createElement('p', { key: 2 }, 'foo')
83+
]
84+
);
85+
});
86+
7087
});

test/html-to-react.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ describe('html-to-react parser', function() {
3030
assert.equal(render(reactElement), html);
3131
});
3232

33+
it('converts single HTML element and ignores comment', function() {
34+
var html = data.html.single;
35+
// comment should be ignored
36+
var reactElement = Parser(html + data.html.comment);
37+
assert.equal(render(reactElement), html);
38+
});
39+
3340
it('converts multiple HTML elements to React', function() {
3441
var html = data.html.multiple;
3542
var reactElements = Parser(html);

0 commit comments

Comments
 (0)