diff --git a/CHANGELOG.md b/CHANGELOG.md index 199c8f52d5..09630c1041 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ This change log adheres to standards from [Keep a CHANGELOG](http://keepachangel ## Unreleased +### Fixed +* [`jsx-no-useless-fragments]: Handle insignificant whitespace correctly when `allowExpressions` is `true` ([#3061][] @benj-dobs) + +[#3061]: https://github.com/yannickcr/eslint-plugin-react/pull/3061 + ## [7.25.1] - 2021.08.29 ### Fixed diff --git a/docs/rules/jsx-no-useless-fragment.md b/docs/rules/jsx-no-useless-fragment.md index b92b83d8ec..a9e6992384 100644 --- a/docs/rules/jsx-no-useless-fragment.md +++ b/docs/rules/jsx-no-useless-fragment.md @@ -64,4 +64,8 @@ Examples of **correct** code for the rule, when `"allowExpressions"` is `true`: ```jsx <>{foo} + +<> + {foo} + ``` diff --git a/lib/rules/jsx-no-useless-fragment.js b/lib/rules/jsx-no-useless-fragment.js index 8cf654ebea..d02e38846d 100644 --- a/lib/rules/jsx-no-useless-fragment.js +++ b/lib/rules/jsx-no-useless-fragment.js @@ -77,10 +77,6 @@ function containsCallExpression(node) { && node.expression.type === 'CallExpression'; } -function isFragmentWithSingleExpression(node) { - return node && node.children.length === 1 && node.children[0].type === 'JSXExpressionContainer'; -} - module.exports = { meta: { type: 'suggestion', @@ -115,6 +111,15 @@ module.exports = { && arrayIncludes(node.raw, '\n'); } + function isFragmentWithSingleExpression(node) { + const children = node && node.children.filter((child) => !isPaddingSpaces(child)); + return ( + children + && children.length === 1 + && children[0].type === 'JSXExpressionContainer' + ); + } + /** * Test whether a JSXElement has less than two children, excluding paddings spaces. * @param {JSXElement|JSXFragment} node diff --git a/tests/lib/rules/jsx-no-useless-fragment.js b/tests/lib/rules/jsx-no-useless-fragment.js index 9dd3487ef5..0557fcdcb0 100644 --- a/tests/lib/rules/jsx-no-useless-fragment.js +++ b/tests/lib/rules/jsx-no-useless-fragment.js @@ -72,6 +72,15 @@ ruleTester.run('jsx-no-useless-fragment', rule, { code: '<>{moo}', parser: parsers.BABEL_ESLINT, options: [{allowExpressions: true}] + }, + { + code: ` + <> + {moo} + + `, + parser: parsers.BABEL_ESLINT, + options: [{allowExpressions: true}] } ], invalid: [