Skip to content

Commit bccf86b

Browse files
committed
Fix destructured props detection in stateless components (fixes #326)
1 parent 1bd8c89 commit bccf86b

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

lib/rules/prop-types.js

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -393,14 +393,22 @@ module.exports = Components.detect(function(context, components, utils) {
393393
break;
394394
case 'VariableDeclarator':
395395
for (var i = 0, j = node.id.properties.length; i < j; i++) {
396-
if (
397-
(node.id.properties[i].key.name !== 'props' && node.id.properties[i].key.value !== 'props') ||
398-
node.id.properties[i].value.type !== 'ObjectPattern'
399-
) {
396+
// let {props: {firstname}} = this
397+
var thisDestructuring = (
398+
(node.id.properties[i].key.name === 'props' || node.id.properties[i].key.value === 'props') &&
399+
node.id.properties[i].value.type === 'ObjectPattern'
400+
);
401+
// let {firstname} = props
402+
var statelessDestructuring = node.init.name === 'props' && utils.getParentStatelessComponent();
403+
404+
if (thisDestructuring) {
405+
properties = node.id.properties[i].value.properties;
406+
} else if (statelessDestructuring) {
407+
properties = node.id.properties;
408+
} else {
400409
continue;
401410
}
402411
type = 'destructuring';
403-
properties = node.id.properties[i].value.properties;
404412
break;
405413
}
406414
break;
@@ -550,7 +558,12 @@ module.exports = Components.detect(function(context, components, utils) {
550558
},
551559

552560
VariableDeclarator: function(node) {
553-
if (!node.init || node.init.type !== 'ThisExpression' || node.id.type !== 'ObjectPattern') {
561+
// let {props: {firstname}} = this
562+
var thisDestructuring = node.init && node.init.type === 'ThisExpression' && node.id.type === 'ObjectPattern';
563+
// let {firstname} = props
564+
var statelessDestructuring = node.init && node.init.name === 'props' && utils.getParentStatelessComponent();
565+
566+
if (!thisDestructuring && !statelessDestructuring) {
554567
return;
555568
}
556569
markPropTypesAsUsed(node);

tests/lib/rules/prop-types.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1376,6 +1376,17 @@ ruleTester.run('prop-types', rule, {
13761376
errors: [{
13771377
message: '\'name\' is missing in props validation'
13781378
}]
1379+
}, {
1380+
code: [
1381+
'var Hello = (props) => {',
1382+
' const {name} = props;',
1383+
' return <div>Hello {name}</div>;',
1384+
'}'
1385+
].join('\n'),
1386+
parser: 'babel-eslint',
1387+
errors: [{
1388+
message: '\'name\' is missing in props validation'
1389+
}]
13791390
}, {
13801391
code: [
13811392
'class Hello extends React.Component {',

0 commit comments

Comments
 (0)