Skip to content

Commit ffe97ce

Browse files
committed
Avoid unsafe autofix when parent is a component
1 parent 0245d24 commit ffe97ce

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

lib/rules/jsx-no-useless-fragment.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,22 @@ module.exports = {
125125
/^[a-z]+$/.test(node.parent.openingElement.name.name);
126126
}
127127

128+
/**
129+
* @param {JSXElement|JSXFragment} node
130+
* @return {boolean}
131+
*/
132+
function isChildOfComponentElement(node) {
133+
return node.parent.type === 'JSXElement' &&
134+
!isChildOfHtmlElement(node) &&
135+
!jsxUtil.isFragment(node.parent, reactPragma, fragmentPragma);
136+
}
137+
128138
/**
129139
* @param {ASTNode} node
130140
* @returns {boolean}
131141
*/
132142
function canFix(node) {
133-
// Fragments that are child elements can always be fixed
143+
// Not safe to fix fragments without a jsx parent.
134144
if (!(node.parent.type === 'JSXElement' || node.parent.type === 'JSXFragment')) {
135145
// const a = <></>
136146
if (node.children.length === 0) {
@@ -143,6 +153,11 @@ module.exports = {
143153
}
144154
}
145155

156+
// Not safe to fix `<Eeee><>foo</></Eeee>` because `Eeee` might require its children be a ReactElement.
157+
if (isChildOfComponentElement(node)) {
158+
return false;
159+
}
160+
146161
return true;
147162
}
148163

tests/lib/rules/jsx-no-useless-fragment.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,9 @@ ruleTester.run('jsx-no-uselses-fragment', rule, {
138138
errors: [{messageId: 'NeedsMoreChidren'}]
139139
},
140140
{
141+
// Not safe to fix this case because `Eeee` might require child be ReactElement
141142
code: '<Eeee><>foo</></Eeee>',
142-
output: '<Eeee>foo</Eeee>',
143+
output: null,
143144
errors: [{messageId: 'NeedsMoreChidren'}],
144145
parser: parsers.BABEL_ESLINT
145146
},

0 commit comments

Comments
 (0)