DEV Community

Discussion on: Are you giving the proper sense to React.Fragment?

Collapse
 
imervinc profile image
👺Mervyn • Edited

IMO:
If your gonna return an empty fragment you might as well return null.
And if your goal is readability, you can always use multiple return like this

function List(props) {  
  const items = props.items;

  // check if items is not empty
  const isEmpty = !(items && items.length > 0);

   if(isEmpty) return null

  return(
      <ul>
        { items.map(i => <li key={i}>{i}</li>) }
      </ul>
      );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
andrewbridge profile image
Andrew Bridge

This is exactly what I came to the comments hoping to post, thanks for getting there first!

I'm baffled to see such a simple example turned into such a lot of code and it exemplifies the over-engineering the React community appears to deal with. Replace null with <React.Fragment /> if you must but creating a list shouldn't take 10s of lines of code.

Collapse
 
sergeysova profile image
Sergey Sova

I prefer this over returning fragment.
But in the most situations we need an empty state component instead of null

Collapse
 
kmturley profile image
Kim T

Multiple returns which both return the same type (html) is the most readable and reusable