Skip to content

Commit ee67f64

Browse files
authored
fix(clone-element): preserve falsy key and ref values in cloneElement (#5082)
* fix(clone-element): preserve falsy key and ref values in cloneElement * fix(clone-element): use UNDEFINED constant and add import * test(clone-element): add tests for falsy key and ref values
1 parent 21dd6d0 commit ee67f64

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

src/clone-element.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { assign, slice } from './util';
22
import { createVNode } from './create-element';
3-
import { NULL } from './constants';
3+
import { NULL, UNDEFINED } from './constants';
44

55
/**
66
* Clones the given VNode, optionally adding attributes/props and replacing its
@@ -31,8 +31,8 @@ export function cloneElement(vnode, props, children) {
3131
return createVNode(
3232
vnode.type,
3333
normalizedProps,
34-
key || vnode.key,
35-
ref || vnode.ref,
34+
key !== UNDEFINED ? key : vnode.key,
35+
ref !== UNDEFINED ? ref : vnode.ref,
3636
NULL
3737
);
3838
}

test/browser/cloneElement.test.jsx

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,23 @@ describe('cloneElement', () => {
8181
const clone = cloneElement(div, { key: 'myKey' });
8282
expect(clone.props.key).to.equal(undefined);
8383
});
84+
85+
it('should preserve falsy key values', () => {
86+
function Foo() {}
87+
const instance = <Foo key="original">hello</Foo>;
88+
89+
let clone = cloneElement(instance, { key: 0 });
90+
expect(clone.key).to.equal(0);
91+
92+
clone = cloneElement(instance, { key: '' });
93+
expect(clone.key).to.equal('');
94+
});
95+
96+
it('should preserve falsy ref values', () => {
97+
function a() {}
98+
const instance = <div ref={a}>hello</div>;
99+
100+
const clone = cloneElement(instance, { ref: null });
101+
expect(clone.ref).to.equal(null);
102+
});
84103
});

0 commit comments

Comments
 (0)