Skip to content

Commit

Permalink
allow the case of fragment with only text and is not child
Browse files Browse the repository at this point in the history
  • Loading branch information
golopot committed Sep 1, 2019
1 parent 14b4cd8 commit 4d8a3f9
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 9 deletions.
6 changes: 4 additions & 2 deletions docs/rules/jsx-no-useless-fragment.md
Expand Up @@ -9,12 +9,12 @@ A fragment is redundant if it contains only one child, or if it is the child of
The following patterns are considered warnings:

```jsx
<>foo</>

<>{foo}</>

<><Foo /></>

<p><>foo</></p>

<></>

<Fragment>foo</Fragment>
Expand All @@ -41,6 +41,8 @@ The following patterns are **not** considered warnings:

<> {foo}</>

const cat = <>meow</>

<SomeComponent>
<>
<div />
Expand Down
13 changes: 12 additions & 1 deletion lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -27,6 +27,17 @@ function isOnlyWhitespace(text) {
return text.trim().length === 0;
}

/**
* Somehow fragment like this is useful: <Foo content={<>ee eeee eeee ...</>} />
* @param {ASTNode} node
* @returns {boolean}
*/
function isFragmentWithOnlyTextAndIsNotChild(node) {
return node.children.length === 1 &&
isJSXText(node.children[0]) &&
!(node.parent.type === 'JSXElement' || node.parent.type === 'JSXFragment');
}

/**
* @param {string} text
* @returns {string}
Expand Down Expand Up @@ -158,7 +169,7 @@ module.exports = {
return;
}

if (hasLessThanTwoChildren(node)) {
if (hasLessThanTwoChildren(node) && !isFragmentWithOnlyTextAndIsNotChild(node)) {
context.report({
node,
messageId: 'NeedsMoreChidren',
Expand Down
10 changes: 4 additions & 6 deletions tests/lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -59,6 +59,10 @@ ruleTester.run('jsx-no-uselses-fragment', rule, {
{
code: '<Fragment key={item.id}>{item.value}</Fragment>',
parser: parsers.BABEL_ESLINT
},
{
code: '<Fooo content={<>eeee ee eeeeeee eeeeeeee</>} />',
parser: parsers.BABEL_ESLINT
}
],
invalid: [
Expand All @@ -68,12 +72,6 @@ ruleTester.run('jsx-no-uselses-fragment', rule, {
errors: [{messageId: 'NeedsMoreChidren', type: 'JSXFragment'}],
parser: parsers.BABEL_ESLINT
},
{
code: '<>foo</>',
output: null,
errors: [{messageId: 'NeedsMoreChidren'}],
parser: parsers.BABEL_ESLINT
},
{
code: '<p>moo<>foo</></p>',
output: '<p>moofoo</p>',
Expand Down

0 comments on commit 4d8a3f9

Please sign in to comment.