no-useless-fragment
Disallows useless fragment elements.
Full Name in eslint-plugin-react-x
react-x/no-useless-fragmentFull Name in @eslint-react/eslint-plugin
@eslint-react/no-useless-fragmentFeatures
🔧 ⚙️
Presets
strict
strict-typescript
strict-type-checked
Rule Details
A fragment is redundant if it contains only one child or if it is the child of an HTML element and is not a keyed fragment.
Common Violations
Invalid
<><Foo /></>
<p><>foo</></p>
<></>
<section>
<>
<div />
<div />
</>
</section>Valid
{foo}
<Foo />
<>
<Foo />
<Bar />
</>
<>foo {bar}</>
<> {foo}</>
<>{children}</>
<>{props.children}</>
const cat = <>meow</>
<SomeComponent>
<>
<div />
<div />
</>
</SomeComponent>
<Fragment key={item.id}>{item.value}</Fragment>Rule Options
type Options = {
allowEmptyFragment?: boolean;
allowExpressions?: boolean;
};allowEmptyFragment
When set to true, allows fragments that contain no children.
Default: false
allowExpressions
When set to true, allows fragments that contain a single expression child.
Default: true
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 behavior, use the allowExpressions option.
Examples of correct code for single expressions in fragments
<>{foo}</>
<Fragment>{foo}</Fragment>Resources
Further Reading
- React Docs:
Fragment - React Docs: Preserving and Resetting State
- GitHub Gist:
clemmy/react_state_preservation_behavior
See Also
react-x/jsx-shorthand-fragment
Enforces shorthand syntax for fragment elements.