Give context for owners of compenent instantiations with propType errors
See modification to the test-file: Basically we add a small hint at the end of the error warning for propType errors to help identify which instantiation of the component at hand is faulty.
Yuval Dekel committed
Jul 2, 2014 at 12:45 UTC
40b522c498a138d3ee5e7729e8e9f330feef88aa
2 files changed
+39
-1
src/core/ReactCompositeComponent.js
+14
-1
@@ -385,6 +385,15 @@ var RESERVED_SPEC_KEYS = {
385
}
386
};
387
388
+function getDeclarationErrorAddendum(component) {
389
+ var owner = component._owner || null;
390
+ if (owner && owner.constructor && owner.constructor.displayName) {
391
+ return ' Check the render method of `' + owner.constructor.displayName +
392
+ '`.';
393
+ }
394
+ return '';
395
+}
396
+
397
function validateTypeDef(Constructor, typeDef, location) {
398
for (var propName in typeDef) {
399
if (typeDef.hasOwnProperty(propName)) {
@@ -967,7 +976,11 @@ var ReactCompositeComponentMixin = {
976
var error =
977
propTypes[propName](props, propName, componentName, location);
978
if (error instanceof Error) {
970
- warning(false, error.message);
979
+ // We may want to extend this logic for similar errors in
980
+ // renderComponent calls, so I'm abstracting it away into
981
+ // a function to minimize refactoring in the future
982
+ var addendum = getDeclarationErrorAddendum(this);
983
+ warning(false, error.message + addendum);
984
}
985
}
986
}
src/core/__tests__/ReactCompositeComponent-test.js
+25
@@ -110,6 +110,31 @@ describe('ReactCompositeComponent', function() {
110
console.warn = warn;
111
});
112
113
+ it('should give context for PropType errors in nested components.', () => {
114
+ // In this test, we're making sure that if a proptype error is found in a
115
+ // component, we give a smal hint as to which parent instantiated that
116
+ // component as per warnings about key-usage in ReactDescriptorValidator.
117
+ spyOn(console, 'warn');
118
+ var MyComp = React.createClass({
119
+ propTypes: {
120
+ color: ReactPropTypes.string
121
+ },
122
+ render: function() {
123
+ return <div>My color is {this.color}</div>;
124
+ }
125
+ });
126
+ var ParentComp = React.createClass({
127
+ render: function() {
128
+ return <MyComp color={123} />;
129
+ }
130
+ });
131
+ ReactTestUtils.renderIntoDocument(<ParentComp />);
132
+ expect(console.warn.calls[0].args[0]).toBe(
133
+ 'Warning: Invalid prop `color` of type `number` supplied to `MyComp`, ' +
134
+ 'expected `string`. Check the render method of `ParentComp`.'
135
+ );
136
+ });
137
+
138
it('should support rendering to different child types over time', function() {
139
var instance = <MorphingComponent />;
140
instance = ReactTestUtils.renderIntoDocument(instance);