React v16.2.0: Improved Support for Fragments

Original Post

Finally! Been waiting for this for a while.

React is shipping improved support for returning Fragments (which, incidentally, I think is a somewhat confusing name, because it isn’t a fragment itself, but the ability to return multiple children without an arbitrary wrapper).

Previously in React, it was necessary to wrap multiple children in a container like a div. This can have annoying effects on markup and styling, and generally just causes unnecessary markup and complexity.

Fragment support allows you to return multiple components without a wrapper.

 render() {
   return (
       <ChildA />
       <ChildB />
       <ChildC />

Woo hoo! See, so much excitement for something so seemingly innocuous.

I did understand the hesitation to provide this feature. It can easily be abused. If you return a ul, return the ul with the list items, problem solved. It would be really dumb if people start returning some list items and not others just because they can.

But what if you want to return two paragraphs of text but don’t want to wrap two p tags for no reason? This feature definitely has it’s uses, as long as people don’t go nuts with it (which of course, they will, but hey! why should the rest of us miss out because a few dummies do dumb things.

Another example from the announcement that also supports the fragment tag instead of an empty tag:

render() {
 return (
     Some text.
     <h2>A heading</h2>
     More text.
     <h2>Another heading</h2>
     Even more text.

Anyways, this is welcome news and the React team continues to impress.


Leave a Reply

%d bloggers like this: