Skip to content

Commit b86a350

Browse files
Remove key parameter from replace and use React.cloneElement
The previous implementation was to pass the `key` as the 2nd parameter in `replace` method and force the user to set the "key" prop in their custom React element. This creates further complexity for the end-user. As a result, use `React.cloneElement` which does the same thing without additional work from the user. `React.cloneElement` takes the React element and merges the "key" prop taken from the array index with the original element's props when applicable. https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement
1 parent ddd289b commit b86a350

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

lib/dom-to-react.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,14 @@ function domToReact(nodes, options) {
2828

2929
// replace with custom React element (if applicable)
3030
if (isReplacePresent) {
31-
replacement = options.replace(node, i); // i = key
31+
replacement = options.replace(node);
3232

3333
if (React.isValidElement(replacement)) {
34+
// specify a "key" prop if element has siblings
35+
// https://fb.me/react-warning-keys
36+
if (len > 1) {
37+
replacement = React.cloneElement(replacement, { key: i });
38+
}
3439
result.push(replacement);
3540
continue;
3641
}

test/html-to-react.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,9 @@ describe('html-to-react', function() {
7777
it('overrides the element if replace is valid', function() {
7878
var html = data.html.complex;
7979
var reactElement = Parser(html, {
80-
replace: function(node, key) {
80+
replace: function(node) {
8181
if (node.name === 'title') {
82-
return React.createElement('title', { key: key }, 'Replaced Title');
82+
return React.createElement('title', {}, 'Replaced Title');
8383
}
8484
}
8585
});

0 commit comments

Comments
 (0)