Fragment in React

Raja Raghav
Programming sage
Published in
2 min readOct 31, 2018

--

When I started doing react back in 2017, It was a love at first line. I literally, felt I could write all of my frontend code in react. But the thing that nagged me the most was the extra set of divs you must add to components with multiple parent nodes. It was a bit irritating and redundant, especially, if you are coming from an HTML background. We usually, don’t wrap elements there. If you don’t know what this all means, here, take a look.

This gives an error in react.

VirtualDOM expects a single parent node from components. So, react developers usually had to wrap them inside a redundant div element to remove the error and get the code working.

The quick-fix, wrapping everything inside a div.

Thankfully, in react v16, the Facebook team came up with a permanent fix for this problem. The solution is called Fragment.

Fragment

Fragment is the solution to this whole “wrapping everything inside one parent situation”. It’s pretty simple, instead of <div> you wrap everything inside a <Fragment>. Hey, that didn’t make any difference! You might say, but this where the magic happens. All <Fragment> tags are automatically removed by react during the final rendering of the DOM. So, your code looks exactly the way it’s meant to be.

Using Fragment

Using fragment is pretty straightforward and simple. You just need to upgrade to react v16+. Then, import {Fragment} from ‘react’ and off you go, use Fragments anywhere in your jsx now.

Fragment in action.

That’s all Folks.

Thanks for reading the article. You can find a working demo of Fragment in react here.

Happy Coding.

--

--