Skip to content

Commit

Permalink
[Fix] jsx-no-useless-fragment: avoid a crash when autofixing a self…
Browse files Browse the repository at this point in the history
…-closing React.Fragment

Fixes #2680.
  • Loading branch information
ljharb committed Jun 29, 2020
1 parent a9d2621 commit d2a131a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/rules/jsx-no-useless-fragment.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,8 @@ module.exports = {
return function fix(fixer) {
const opener = node.type === 'JSXFragment' ? node.openingFragment : node.openingElement;
const closer = node.type === 'JSXFragment' ? node.closingFragment : node.closingElement;
const childrenText = context.getSourceCode().getText().slice(opener.range[1], closer.range[0]);

const childrenText = opener.selfClosing ? '' : context.getSourceCode().getText().slice(opener.range[1], closer.range[0]);

return fixer.replaceText(node, trimLikeReact(childrenText));
};
Expand Down
19 changes: 18 additions & 1 deletion tests/lib/rules/jsx-no-useless-fragment.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const parserOptions = {

const ruleTester = new RuleTester({parserOptions});

ruleTester.run('jsx-no-uselses-fragment', rule, {
ruleTester.run('jsx-no-useless-fragment', rule, {
valid: [
{
code: '<><Foo /><Bar /></>',
Expand Down Expand Up @@ -201,6 +201,23 @@ ruleTester.run('jsx-no-uselses-fragment', rule, {
output: '<div>a {""}{""} a</div>',
errors: [{messageId: 'ChildOfHtmlElement'}],
parser: parsers.BABEL_ESLINT
},
{
code: `
const Comp = () => (
<html>
<React.Fragment />
</html>
);
`,
output: `
const Comp = () => (
<html>
${/* the trailing whitespace here is intentional */ ''}
</html>
);
`,
errors: [{messageId: 'NeedsMoreChidren'}, {messageId: 'ChildOfHtmlElement'}]
}
]
});

0 comments on commit d2a131a

Please sign in to comment.