Skip to content

Commit 2e27797

Browse files
Specify "key" prop when creating an array of children
Fix the following in DOM to React parser: > Warning: Each child in an array should have a unique "key" prop. > See https://fb.me/react-warning-keys for more information. Add test to check for this use case with parsing multiple/sibling elements.
1 parent a18f353 commit 2e27797

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

lib/dom-to-react.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@ function domToReact(nodes) {
3232
children = domToReact(node.children);
3333
}
3434

35+
// specify a `key` prop if returning an array
36+
// https://fb.me/react-warning-keys
37+
if (len > 1) {
38+
node.attribs.key = i;
39+
}
40+
3541
result.push(
3642
React.createElement(
3743
node.name,

test/data.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"html": {
33
"single": "<p>foo</p>",
4+
"multiple": "<p>foo</p><p>bar</p>",
45
"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>"
56
}
67
}

test/dom-to-react.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,20 @@ describe('dom-to-react parser', function() {
2424
);
2525
});
2626

27+
it('converts multiple DOM nodes to React', function() {
28+
var html = data.html.multiple;
29+
var reactElements = domToReact(htmlToDOM(html));
30+
reactElements.forEach(function(reactElement) {
31+
assert(React.isValidElement(reactElement));
32+
assert(reactElement.key);
33+
});
34+
assert.deepEqual(
35+
reactElements,
36+
[
37+
React.createElement('p', { key: 0 }, 'foo'),
38+
React.createElement('p', { key: 1 }, 'bar')
39+
]
40+
);
41+
});
42+
2743
});

0 commit comments

Comments
 (0)