More helpful message when passing an element to createElement() (#13131)

* [#13130] Add a more helpful message when passing an element to createElement()

* better conditional flow

* update after review

* move last condition inside last else clause

* Added test case

* compare 25132typeof to REACT_ELEMENT_TYPE

* runs prettier

* remove unrelated changes

* Tweak the message
This commit is contained in:
Dylan Cutler
2018-08-01 18:45:08 +01:00
committed by Dan Abramov
parent 28cd494bdf
commit c44c2a2161
2 changed files with 25 additions and 0 deletions
@@ -19,6 +19,7 @@ import {
getIteratorFn,
REACT_FORWARD_REF_TYPE,
REACT_FRAGMENT_TYPE,
REACT_ELEMENT_TYPE,
} from 'shared/ReactSymbols';
import checkPropTypes from 'prop-types/checkPropTypes';
import warning from 'shared/warning';
@@ -286,6 +287,10 @@ export function createElementWithValidation(type, props, children) {
typeString = 'null';
} else if (Array.isArray(type)) {
typeString = 'array';
} else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
typeString = `<${getComponentName(type.type) || 'Unknown'} />`;
info =
' Did you accidentally export a JSX literal instead of a component?';
} else {
typeString = typeof type;
}
@@ -229,12 +229,17 @@ describe('ReactElementValidator', () => {
});
it('gives a helpful error when passing invalid types', () => {
function Foo() {}
expect(() => {
React.createElement(undefined);
React.createElement(null);
React.createElement(true);
React.createElement({x: 17});
React.createElement({});
React.createElement(React.createElement('div'));
React.createElement(React.createElement(Foo));
React.createElement(React.createElement(React.createContext().Consumer));
React.createElement({$$typeof: 'non-react-thing'});
}).toWarnDev(
[
'Warning: React.createElement: type is invalid -- expected a string ' +
@@ -256,6 +261,21 @@ describe('ReactElementValidator', () => {
'components) but got: object. You likely forgot to export your ' +
"component from the file it's defined in, or you might have mixed up " +
'default and named imports.',
'Warning: React.createElement: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: <div />. Did you accidentally export a JSX literal ' +
'instead of a component?',
'Warning: React.createElement: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: <Foo />. Did you accidentally export a JSX literal ' +
'instead of a component?',
'Warning: React.createElement: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: <Context.Consumer />. Did you accidentally ' +
'export a JSX literal instead of a component?',
'Warning: React.createElement: type is invalid -- expected a string ' +
'(for built-in components) or a class/function (for composite ' +
'components) but got: object.',
],
{withoutStack: true},
);