no-useless-fragment

Try in Playground
react-best-practicesBest PracticeInformational

0

No tags

No CWE or CVE

This rule detects when you have a fragment that's redundant.

A fragment is considered redundant when it contains only one child or if it's a child of an HTML element, and is not a keyed fragment

View a similar rule from ESLint: react/jsx-no-useless-fragment

Ast Rule: html element


no-useless-fragment

How to write a rule
function checkIfFragment(tag) {
  if (tag === null) return true;
  if (tag.value === "Fragment") return true;
  if (tag.value === "React.Fragment") return true;
  return false;
}

function visit(node, filename, code) {
  if (!node) return;
	return

  // we won't check tags that aren't fragments
  const isFragment = checkIfFragment(node.tag);

  // check if a fragment is the only thing in an html element
  // if (node.tag?.value[0] === node.tag?.value[0].toLowerCase()) {
  //     node.htmlChildren.forEach(child => {
  //       if (child.tag === null) {
  //         const error = buildError(
  //           child.start.line,
  //           child.start.col,
  //           child.end.line,
  //           child.end.col,
  //           `useless React Fragment`,
  //           "INFORMATIONAL",
  //           "BEST_PRACTICE"
  //         );

  //         addError(error);
  //         return
  //       }
  //     })
  //   }

  // if it's not a fragment exit
  if (!isFragment) return;

  // if it's a fragment but has a key prop, skip it
  if (node.tag && node.attributes.some(attribute => attribute.name.value === "key")) return;

  // if there's more than one child, then the fragment is needed
  if (node.content.length > 1) return;

  const error = buildError(
    node.start.line,
    node.start.col,
    node.end.line,
    node.end.col,
    `useless React Fragment`,
    "INFORMATIONAL",
    "BEST_PRACTICE"
  );

  addError(error);
}

incorrect-usage.jsx

Expected test result: has error

React fragments with one child

<>{foo}</>

<><Foo /></>

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

<></>

<Fragment>foo</Fragment>

<React.Fragment>foo</React.Fragment>

<div>
	{showFullName ? <>{fullName}</> : <>{firstName}</>}	
</div>

<div>
	<>
		{showFullName ? fullName : firstName}	
	</>
</div>

correct-usage.jsx

Expected test result: no error

React fragments with two children

{foo}

<Foo />

<>
  <Foo />
  <Bar />
</>

<SomeComponent>
  <>
    <div />
    <div />
  </>
</SomeComponent>

<Fragment key={item.id}>{item.value}</Fragment>

{showFullName ? fullName : firstName}
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.