Back
Blog Post|#engineering

Clear the Clutter with Fragments

Jenn RobisonThursday, December 12, 2019
An top view of a woman's desk with 2 monitors and a laptop.

I have been developing React Native applications for about two years, and until just recently I had no knowledge of fragments. I found myself doing a peer review with some empty element tags and I thought it might be a mistake. I took to Google and quickly found an article from reactjs.org announcing fragment support in v16.2.0. I was so excited! In my early days of React Native development, I found myself frustrated that I would have to wrap sets of elements in a just to satisfy the JSX expression.

This is a game-changer for me! It reduces the complexity and increases the readability of your code. There is no uncertainty if that View is necessary and how it might be affecting the rendering of your screen or component.

Take this as an example. I have a screen that I may or may not render a couple of lines of styled text within another View that is already styled. I create a conditional and tell it to render to more Text elements, but it is not happy with me. My editor is letting me know that the JSX element is expecting all items to be within one containing parent.

React code in Visual Studio Code

Two elements with no parent, and unhappy linter

Parsing error in Visual Studio Code

JSX Parsing error

I can resolve this error by wrapping the two text components inside a container:

React code in Visual Studio Code

JSX contained within a parent element

But why add that extra node in the DOM, along with the baggage it might be brining. In this case, our container is a view, which has style props, etc.

A much cleaner approach is the use of a fragment, which looks like this:

React code in Visual Studio Code

Usage of a fragment

As a developer, I now can see that this is just a way to group these children. I don’t need to dig into that container in order to determine why my text elements are not properly laid out. I’ve also reduced the extra noise in the DOM.

You can also utilize <React.Fragment></React.Fragment>. Personally I think it looks cleaner without. In fact, if you utilize eslint it will actually tell you it prefers the usage of the shorthand <></>.

I’m always up for shortcuts, that save me keystrokes and make for more readable projects!

Share this post

twitterfacebooklinkedin

Related Posts:

Interested in working with us?

Give us some details about your project, and our team will be in touch with how we can help.

Get in Touch