logoESLint React
Rules

no-useless-fragment

Full Name in eslint-plugin-react-x

react-x/no-useless-fragment

Full Name in @eslint-react/eslint-plugin

@eslint-react/no-useless-fragment

Features

🔧 ⚙️

Description

Disallow useless fragment elements.

A fragment is redundant if it contains only one child, or if it is the child of a html element, and is not a keyed fragment.

Moreover, rendering fragments with multiple levels of depth can cause React to not retain the state of components nested within the fragment after certain re-renders, which may lead to unexpected state resetting.

Examples

Failing

<><Foo /></>

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

<></>

<section>
  <>
    <div />
    <div />
  </>
</section>

Passing

{foo}

<Foo />

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

<>foo {bar}</>

<> {foo}</>

<>{children}</>

<>{props.children}</>

const cat = <>meow</>

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

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

Note

By default, this rule always allows single expressions in a fragment. This is useful in places like Typescript where string does not satisfy the expected return type of JSX.Element. A common workaround is to wrap the variable holding a string in a fragment and expression. To change this behaviour, use the allowExpressions option.

Examples of correct code for single expressions in fragments

<>{foo}</>

<Fragment>{foo}</Fragment>

Examples with allowExpressions: false

Failing

<><Foo /></>

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

<></>

<Foo bar={<>baz</>} />

<section>
  <>
    <div />
    <div />
  </>
</section>

const cat = <>meow</>

<>{children}</>

<>{props.children}</>

<> {foo}</>

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

Passing

{foo}

<Foo />

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

<>foo {bar}</>

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

Implementation

Further Reading

On this page