eslint-plugin-react: react/jsx-no-useless-fragment false positive
There’s a false positive on the rule with forwarded children. Use cases are pretty rare but still exist. Without a fragment around the children, code breaks at runtime
const HollowComponent = ({ children }) => {
// some logic here
return <>{children}</>; // doesn't pass the rule
}
example: https://codesandbox.io/s/icy-lake-ri3uo
Temporary fix is to disable rule for this line but it would be nicer if this rule let this kind of Fragment use possible.
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 20
- Comments: 15 (5 by maintainers)
Commits related to this issue
- CFIN-289: Refactor to tidy up conditional rendering of error msg There's an XO error about a fragment only having one child. Seems like a false positive to me, because that one child is actually a ".... — committed to university-of-york/uoy-app-course-search by FergusMcGlynn 4 years ago
- CFIN-289: Disable XO rule to deal with false positive bug There is an issue where XO reports a "jsx-no-useless-fragment" error when encountering a fragment that contains a ".map()" - it interprets th... — committed to university-of-york/uoy-app-course-search by FergusMcGlynn 4 years ago
- [New] `jsx-no-useless-fragment`: support `ignoreNeedsMoreChildren` option With `ignoreNeedsMoreChildren` enabled, this rule will only warn about useless fragments that removing would guarantee no cha... — committed to sbdchd/eslint-plugin-react by sbdchd 3 years ago
For me the solution was to add
allowExpressionsoption to the config:Hi, I think I have encountered a similar problem. My use case is like this:
This is treated as an error but the render prop expects the return to be a single element so I think the Fragment is necessary here.
allowExpressions: true is not work for me
Thanks for bearing with me.
Type errors aren’t relevant, but runtime errors are.
The solution in your code, of course, is to use defaultProps, or
const TestEmpty = ({ children = null }) => children;, so that if it is undefined, it becomesnull, or,const TestEmpty = ({ children }) => children ?? null;, but it seems reasonable to have an option to specifically allow a prop, only, to be used with an otherwise “unnecessary” fragment, because ofundefined.As you can see in the codesandbox I pasted in the original post ( https://codesandbox.io/s/suspicious-sunset-ly9ik ), returning the children without a fragment can throw a runtime error (in case no children are provided).
Working with typescript generates an error too as children type for a
FunctionalComponentcan be undefined and said functional component cannot return the undefined type.In the first case, why wouldn’t
: childrenwork identically?Same question in the second case;
return childrenshould work fine.