Skip to content

Commit 70cebe4

Browse files
committed
Fix stateless components detection when conditionally returning JSX (fixes #486)
1 parent 8df4123 commit 70cebe4

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

lib/util/Components.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ function componentRule(rule, context) {
165165
/**
166166
* Check if the node is returning JSX
167167
*
168-
* @param {ASTNode} node The AST node being checked (must be a ReturnStatement).
168+
* @param {ASTNode} node The AST node being checked (can be a ReturnStatement or an ArrowFunctionExpression).
169169
* @returns {Boolean} True if the node is returning JSX, false if not
170170
*/
171171
isReturningJSX: function(node) {
@@ -181,6 +181,16 @@ function componentRule(rule, context) {
181181
return false;
182182
}
183183

184+
var returnsConditionalJSXConsequent =
185+
node[property] &&
186+
node[property].type === 'ConditionalExpression' &&
187+
node[property].consequent.type === 'JSXElement'
188+
;
189+
var returnsConditionalJSXAlternate =
190+
node[property] &&
191+
node[property].type === 'ConditionalExpression' &&
192+
node[property].alternate.type === 'JSXElement'
193+
;
184194
var returnsJSX =
185195
node[property] &&
186196
node[property].type === 'JSXElement'
@@ -192,7 +202,12 @@ function componentRule(rule, context) {
192202
node[property].callee.property.name === 'createElement'
193203
;
194204

195-
return Boolean(returnsJSX || returnsReactCreateElement);
205+
return Boolean(
206+
returnsConditionalJSXConsequent ||
207+
returnsConditionalJSXAlternate ||
208+
returnsJSX ||
209+
returnsReactCreateElement
210+
);
196211
},
197212

198213
/**

tests/lib/rules/prop-types.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,6 +1998,14 @@ ruleTester.run('prop-types', rule, {
19981998
errors: [{
19991999
message: '\'toggle\' is missing in props validation'
20002000
}]
2001+
}, {
2002+
code: [
2003+
'const MyComponent = props => props.test ? <div /> : <span />'
2004+
].join('\n'),
2005+
parserOptions: parserOptions,
2006+
errors: [{
2007+
message: '\'test\' is missing in props validation'
2008+
}]
20012009
}
20022010
]
20032011
});

0 commit comments

Comments
 (0)