Throw more specific error if passed undefined in React.cloneElement (#12534)
* throw error if passed undefined * should be TypeError * simplify * use invariant * editor messed up spacing * better check * Revert "better check" This reverts commit 273370758eafa54d329577b3dc942c70587eccd3. * yarn prettier test was failing * more explicit copy * es6 import * tests * formatting * Move import
Nicole Levy committed
Apr 9, 2018 at 21:16 UTC
f88deda83bab316385f39e8479850527cda90607
2 files changed
+21
packages/react/src/ReactElement.js
+7
@@ -5,6 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
+import invariant from 'fbjs/lib/invariant';
9
import warning from 'fbjs/lib/warning';
10
import {REACT_ELEMENT_TYPE} from 'shared/ReactSymbols';
11
@@ -290,6 +291,12 @@ export function cloneAndReplaceKey(oldElement, newKey) {
291
* See https://reactjs.org/docs/react-api.html#cloneelement
292
*/
293
export function cloneElement(element, config, children) {
294
+ invariant(
295
+ !(element === null || element === undefined),
296
+ 'React.cloneElement(...): The argument must be a React element, but you passed %s.',
297
+ element,
298
+ );
299
+
300
let propName;
301
302
// Original props are copied
packages/react/src/__tests__/ReactElementClone-test.js
+14
@@ -359,4 +359,18 @@ describe('ReactElementClone', () => {
359
}
360
expect(clone.props).toEqual({foo: 'ef'});
361
});
362
+
363
+ it('throws an error if passed null', () => {
364
+ const element = null;
365
+ expect(() => React.cloneElement(element)).toThrow(
366
+ 'React.cloneElement(...): The argument must be a React element, but you passed null.',
367
+ );
368
+ });
369
+
370
+ it('throws an error if passed undefined', () => {
371
+ let element;
372
+ expect(() => React.cloneElement(element)).toThrow(
373
+ 'React.cloneElement(...): The argument must be a React element, but you passed undefined.',
374
+ );
375
+ });
376
});