[react/jsx-no-useless-fragments] add option to allow single expressions in fragments #3006
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Problem
When writing JSX in typescript, a common problem is that Typescript expects the return type of a component to be
ReactElement
. This excludes other types that a component could return, for example just a plain string. This is a problem that's been discussed with the TS community here: 21699, however my understanding is there are technical barriers to overcome in order to support this.A common workaround for this is to wrap a variable in a fragment and expression to get the desired result:
This works well (even if it introduces a small amount of overhead in React), but triggers the
jsx-no-useless-fragments
rule, because as far as eslint is concerned, this is a useless fragment in javascript.Solution
I'm proposing that we add an option to allow single expressions for Typescript users that want to employ this workaround. I went with an extra option because the original behaviour still makes sense in plain Javascript, and this is a behaviour only Typescript users would find useful.
(also fixed a typo from
NeedsMoreChidren
->NeedsMoreChildren
. Took me a while to figure out why the tests weren't passing thanks to that typo 😅)