Skip to content

Commit

Permalink
Avoid unsafe autofix when parent is a component
Browse files Browse the repository at this point in the history
  • Loading branch information
golopot committed Sep 5, 2019
1 parent 0245d24 commit ffe97ce
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
17 changes: 16 additions & 1 deletion lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -125,12 +125,22 @@ module.exports = {
/^[a-z]+$/.test(node.parent.openingElement.name.name);
}

/**
* @param {JSXElement|JSXFragment} node
* @return {boolean}
*/
function isChildOfComponentElement(node) {
return node.parent.type === 'JSXElement' &&
!isChildOfHtmlElement(node) &&
!jsxUtil.isFragment(node.parent, reactPragma, fragmentPragma);
}

/**
* @param {ASTNode} node
* @returns {boolean}
*/
function canFix(node) {
// Fragments that are child elements can always be fixed
// Not safe to fix fragments without a jsx parent.
if (!(node.parent.type === 'JSXElement' || node.parent.type === 'JSXFragment')) {
// const a = <></>
if (node.children.length === 0) {
Expand All @@ -143,6 +153,11 @@ module.exports = {
}
}

// Not safe to fix `<Eeee><>foo</></Eeee>` because `Eeee` might require its children be a ReactElement.
if (isChildOfComponentElement(node)) {
return false;
}

return true;
}

Expand Down
3 changes: 2 additions & 1 deletion tests/lib/rules/jsx-no-useless-fragment.js
Expand Up @@ -138,8 +138,9 @@ ruleTester.run('jsx-no-uselses-fragment', rule, {
errors: [{messageId: 'NeedsMoreChidren'}]
},
{
// Not safe to fix this case because `Eeee` might require child be ReactElement
code: '<Eeee><>foo</></Eeee>',
output: '<Eeee>foo</Eeee>',
output: null,
errors: [{messageId: 'NeedsMoreChidren'}],
parser: parsers.BABEL_ESLINT
},
Expand Down

0 comments on commit ffe97ce

Please sign in to comment.