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

Most upvoted comments

For me the solution was to add allowExpressions option to the config:

"react/jsx-no-useless-fragment": [2, { allowExpressions: true }]

Hi, I think I have encountered a similar problem. My use case is like this:

<Query>
  {({data, loading})  => {
    ...
    return (
      <>
        {anArray.map(item => {
          return item.success
            ? getTypeA(item)
            : getTypeB(item);
        })}
      </>
    );
  }
}
</Query>

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 becomes null, 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 of undefined.

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 FunctionalComponent can be undefined and said functional component cannot return the undefined type.

In the first case, why wouldn’t : children work identically?

Same question in the second case; return children should work fine.