Skip to content

Commit

Permalink
[Fix] jsx-no-useless-fragment: accept fragments with call expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
hasparus authored and ljharb committed Aug 6, 2020
1 parent de268ec commit a77c0d1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
26 changes: 20 additions & 6 deletions lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -66,6 +66,17 @@ function isKeyedElement(node) {
&& node.openingElement.attributes.some(jsxUtil.isJSXAttributeKey);
}

/**
* @param {ASTNode} node
* @returns {boolean}
*/
function containsCallExpression(node) {
return node
&& node.type === 'JSXExpressionContainer'
&& node.expression
&& node.expression.type === 'CallExpression';
}

module.exports = {
meta: {
type: 'suggestion',
Expand Down Expand Up @@ -103,15 +114,18 @@ module.exports = {
* @returns {boolean}
*/
function hasLessThanTwoChildren(node) {
if (!node || !node.children || node.children.length < 2) {
if (!node || !node.children) {
return true;
}

return (
node.children.length
- (+isPaddingSpaces(node.children[0]))
- (+isPaddingSpaces(node.children[node.children.length - 1]))
) < 2;
/** @type {ASTNode[]} */
const nonPaddingChildren = node.children.filter(
(child) => !isPaddingSpaces(child)
);

if (nonPaddingChildren.length < 2) {
return !containsCallExpression(nonPaddingChildren[0]);
}
}

/**
Expand Down
10 changes: 10 additions & 0 deletions tests/lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -63,6 +63,10 @@ ruleTester.run('jsx-no-useless-fragment', rule, {
{
code: '<Fooo content={<>eeee ee eeeeeee eeeeeeee</>} />',
parser: parsers.BABEL_ESLINT
},
{
code: '<>{foos.map(foo => foo)}</>',
parser: parsers.BABEL_ESLINT
}
],
invalid: [
Expand All @@ -72,6 +76,12 @@ ruleTester.run('jsx-no-useless-fragment', rule, {
errors: [{messageId: 'NeedsMoreChidren', type: 'JSXFragment'}],
parser: parsers.BABEL_ESLINT
},
{
code: '<>{}</>',
output: null,
errors: [{messageId: 'NeedsMoreChidren', type: 'JSXFragment'}],
parser: parsers.BABEL_ESLINT
},
{
code: '<p>moo<>foo</></p>',
output: '<p>moofoo</p>',
Expand Down

0 comments on commit a77c0d1

Please sign in to comment.