Skip to content

Commit

Permalink
Warn if class has a render() method but doesn't extend React.Component (
Browse files Browse the repository at this point in the history
facebook#11168)

Warn if class has a render() method but doesn't extend React.Component
  • Loading branch information
swyxio authored and Ethan-Arrowood committed Dec 8, 2017
1 parent 151b778 commit ed86315
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
20 changes: 20 additions & 0 deletions packages/react-dom/src/__tests__/ReactCompositeComponent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,26 @@ describe('ReactCompositeComponent', () => {
expect(cbCalled).toBe(false);
});

it('should warn when rendering a class with a render method that does not extend React.Component', () => {
spyOn(console, 'error');
var container = document.createElement('div');
class ClassWithRenderNotExtended {
render() {
return <div />;
}
}
expectDev(console.error.calls.count()).toBe(0);
expect(() => {
ReactDOM.render(<ClassWithRenderNotExtended />, container);
}).toThrow(TypeError);
expectDev(console.error.calls.count()).toBe(1);
expectDev(console.error.calls.argsFor(0)[0]).toContain(
'Warning: The <ClassWithRenderNotExtended /> component appears to have a render method, ' +
"but doesn't extend React.Component. This is likely to cause errors. " +
'Change ClassWithRenderNotExtended to extend React.Component instead.',
);
});

it('should warn about `setState` in render', () => {
spyOn(console, 'error');

Expand Down
11 changes: 11 additions & 0 deletions packages/react-reconciler/src/ReactFiberBeginWork.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ var {
} = require('shared/ReactTypeOfSideEffect');
var {ReactCurrentOwner} = require('shared/ReactGlobalSharedState');
var invariant = require('fbjs/lib/invariant');
var getComponentName = require('shared/getComponentName');

var ReactFiberClassComponent = require('./ReactFiberClassComponent');
var {
Expand Down Expand Up @@ -471,6 +472,16 @@ module.exports = function<T, P, I, TI, PI, C, CC, CX, PL>(
var value;

if (__DEV__) {
if (fn.prototype && typeof fn.prototype.render === 'function') {
const componentName = getComponentName(workInProgress);
warning(
false,
"The <%s /> component appears to have a render method, but doesn't extend React.Component. " +
'This is likely to cause errors. Change %s to extend React.Component instead.',
componentName,
componentName,
);
}
ReactCurrentOwner.current = workInProgress;
value = fn(props, context);
} else {
Expand Down

0 comments on commit ed86315

Please sign in to comment.