React.isValidClass

Sometimes you may need to detect if a value is a valid React class constructor. This enables that and prevents future consumers from getting caught in the trap of depending on an internal implementation detail we might change.

Currently this works for classes created with `React.createClass` as well as `React.DOM.*`.
This commit is contained in:
Paul O'Shannessy
2013-08-30 13:20:51 -07:00
committed by Paul O’Shannessy
parent 0db4077c3a
commit 4d8f0449d9
4 changed files with 46 additions and 3 deletions
+1
View File
@@ -50,6 +50,7 @@ var React = {
),
renderComponentToString: ReactServerRendering.renderComponentToString,
unmountAndReleaseReactRootNode: ReactMount.unmountAndReleaseReactRootNode,
isValidClass: ReactCompositeComponent.isValidClass,
isValidComponent: ReactComponent.isValidComponent
};
+13
View File
@@ -956,6 +956,19 @@ var ReactCompositeComponent = {
return ConvenienceConstructor;
},
/**
* Checks if a value is a valid component constructor.
*
* @param {*}
* @return {boolean}
* @public
*/
isValidClass: function(componentClass) {
return componentClass instanceof Function &&
'componentConstructor' in componentClass &&
componentClass.componentConstructor instanceof Function;
},
/**
* TODO: Delete this when all callers have been updated to rely on this
* behavior being the default.
@@ -381,4 +381,30 @@ describe('ReactCompositeComponent', function() {
);
});
it('should detect valid CompositeComponent classes', function() {
var Component = React.createClass({
render: function() {
return <div/>;
}
});
expect(React.isValidClass(Component)).toBe(true);
});
it('should detect invalid CompositeComponent classes', function() {
var FnComponent = function() {
return false;
}
var NullComponent = null;
var TrickFnComponent = function() {
return true;
}
TrickFnComponent.componentConstructor = true;
expect(React.isValidClass(FnComponent)).toBe(false);
expect(React.isValidClass(NullComponent)).toBe(false);
expect(React.isValidClass(TrickFnComponent)).toBe(false);
});
});
+6 -3
View File
@@ -23,11 +23,10 @@
var React = require('React');
var ReactDOM = require('ReactDOM');
var ReactTestUtils = require('ReactTestUtils');
var React = require('React');
var ReactMount = require('ReactMount');
var ReactTestUtils = require('ReactTestUtils');
describe('ref swapping', function() {
describe('ReactDOM', function() {
// TODO: uncomment this test once we can run in phantom, which
// supports real submit events.
/*
@@ -115,4 +114,8 @@ describe('ref swapping', function() {
var dog = root.childNodes[0];
expect(dog.className).toBe('bigdog');
});
it('should be a valid class', function() {
expect(React.isValidClass(ReactDOM.div)).toBe(true);
});
});