Skip to content

Commit

Permalink
Fix usage of propTypes with an external object (fixes #9)
Browse files Browse the repository at this point in the history
  • Loading branch information
yannickcr committed Mar 22, 2015
1 parent f7792b3 commit ade2c05
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
8 changes: 8 additions & 0 deletions docs/rules/prop-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,12 @@ var Hello = React.createClass({
return <div>Hello {this.props.name}</div>;
}
});

// Referencing an external object disable the rule for the component
var Hello = React.createClass({
propTypes: myPropTypes,
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
```
14 changes: 11 additions & 3 deletions lib/rules/prop-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ module.exports = function(context) {

var declaredPropTypes = [];
var usedPropTypes = [];
var ignorePropsValidation = false;

function isComponentDefinition(node) {
return (
Expand Down Expand Up @@ -48,6 +49,11 @@ module.exports = function(context) {
if (keyName !== 'propTypes') {
return;
}
if (property.value.type !== 'ObjectExpression') {
ignorePropsValidation = true;
return;
}

for (var i = 0, j = property.value.properties.length; i < j; i++) {
declaredPropTypes.push(property.value.properties[i].key.name);
}
Expand All @@ -60,14 +66,16 @@ module.exports = function(context) {
return;
}

for (var i = 0, j = usedPropTypes.length; i < j; i++) {
if (declaredPropTypes.indexOf(usedPropTypes[i]) === -1 && usedPropTypes[i] !== 'children') {
context.report(node, '\'' + usedPropTypes[i] + '\' is missing in props validation');
for (var i = 0, j = usedPropTypes.length; !ignorePropsValidation && i < j; i++) {
if (declaredPropTypes.indexOf(usedPropTypes[i]) !== -1 || usedPropTypes[i] === 'children') {
continue;
}
context.report(node, '\'' + usedPropTypes[i] + '\' is missing in props validation');
}

declaredPropTypes.length = 0;
usedPropTypes.length = 0;
ignorePropsValidation = false;
}
};

Expand Down
11 changes: 11 additions & 0 deletions tests/lib/rules/prop-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,17 @@ eslintTester.addRuleTest('lib/rules/prop-types', {
ecmaFeatures: {
jsx: true
}
}, {
code: '\
var Hello = React.createClass({\
propTypes: externalPropTypes,\
render: function() {\
return <div>Hello {this.props.name}</div>;\
}\
});',
ecmaFeatures: {
jsx: true
}
}
],

Expand Down

0 comments on commit ade2c05

Please sign in to comment.