From aba4f969929c5e765f1597a4706513d8b2fd42ea Mon Sep 17 00:00:00 2001 From: Yannick Croissant Date: Tue, 29 Mar 2016 22:50:24 +0000 Subject: [PATCH] Fix prefer-stateless-function for conditional JSX (fixes #516) --- lib/rules/prefer-stateless-function.js | 2 +- lib/util/Components.js | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/rules/prefer-stateless-function.js b/lib/rules/prefer-stateless-function.js index e7f8a65751..296a1ab6c8 100644 --- a/lib/rules/prefer-stateless-function.js +++ b/lib/rules/prefer-stateless-function.js @@ -209,7 +209,7 @@ module.exports = Components.detect(function(context, components, utils) { } scope = scope.upper; } - if (!blockNode || !blockNode.key || blockNode.key.name !== 'render' || utils.isReturningJSX(node)) { + if (!blockNode || !blockNode.key || blockNode.key.name !== 'render' || utils.isReturningJSX(node, true)) { return; } markReturnAsInvalid(node); diff --git a/lib/util/Components.js b/lib/util/Components.js index 0616c8289b..5e9235e28d 100644 --- a/lib/util/Components.js +++ b/lib/util/Components.js @@ -166,9 +166,10 @@ function componentRule(rule, context) { * Check if the node is returning JSX * * @param {ASTNode} node The AST node being checked (can be a ReturnStatement or an ArrowFunctionExpression). + * @param {Boolean} strict If true, in a ternary condition the node must return JSX in both cases * @returns {Boolean} True if the node is returning JSX, false if not */ - isReturningJSX: function(node) { + isReturningJSX: function(node, strict) { var property; switch (node.type) { case 'ReturnStatement': @@ -191,6 +192,10 @@ function componentRule(rule, context) { node[property].type === 'ConditionalExpression' && node[property].alternate.type === 'JSXElement' ; + var returnsConditionalJSX = + strict ? (returnsConditionalJSXConsequent && returnsConditionalJSXAlternate) : + (returnsConditionalJSXConsequent || returnsConditionalJSXAlternate); + var returnsJSX = node[property] && node[property].type === 'JSXElement' @@ -203,8 +208,7 @@ function componentRule(rule, context) { ; return Boolean( - returnsConditionalJSXConsequent || - returnsConditionalJSXAlternate || + returnsConditionalJSX || returnsJSX || returnsReactCreateElement );