Skip to content

Commit 7f10fae

Browse files
swyxiogaearon
authored andcommitted
Warn if class has a render() method but doesn't extend React.Component (#11168)
Warn if class has a render() method but doesn't extend React.Component
1 parent 4a43cf6 commit 7f10fae

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

packages/react-dom/src/__tests__/ReactCompositeComponent-test.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,26 @@ describe('ReactCompositeComponent', () => {
326326
expect(cbCalled).toBe(false);
327327
});
328328

329+
it('should warn when rendering a class with a render method that does not extend React.Component', () => {
330+
spyOn(console, 'error');
331+
var container = document.createElement('div');
332+
class ClassWithRenderNotExtended {
333+
render() {
334+
return <div />;
335+
}
336+
}
337+
expectDev(console.error.calls.count()).toBe(0);
338+
expect(() => {
339+
ReactDOM.render(<ClassWithRenderNotExtended />, container);
340+
}).toThrow(TypeError);
341+
expectDev(console.error.calls.count()).toBe(1);
342+
expectDev(console.error.calls.argsFor(0)[0]).toContain(
343+
'Warning: The <ClassWithRenderNotExtended /> component appears to have a render method, ' +
344+
"but doesn't extend React.Component. This is likely to cause errors. " +
345+
'Change ClassWithRenderNotExtended to extend React.Component instead.',
346+
);
347+
});
348+
329349
it('should warn about `setState` in render', () => {
330350
spyOn(console, 'error');
331351

packages/react-reconciler/src/ReactFiberBeginWork.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ var {
3939
} = require('shared/ReactTypeOfSideEffect');
4040
var {ReactCurrentOwner} = require('shared/ReactGlobalSharedState');
4141
var invariant = require('fbjs/lib/invariant');
42+
var getComponentName = require('shared/getComponentName');
4243

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

473474
if (__DEV__) {
475+
if (fn.prototype && typeof fn.prototype.render === 'function') {
476+
const componentName = getComponentName(workInProgress);
477+
warning(
478+
false,
479+
"The <%s /> component appears to have a render method, but doesn't extend React.Component. " +
480+
'This is likely to cause errors. Change %s to extend React.Component instead.',
481+
componentName,
482+
componentName,
483+
);
484+
}
474485
ReactCurrentOwner.current = workInProgress;
475486
value = fn(props, context);
476487
} else {

0 commit comments

Comments
 (0)