Clear the Clutter with Fragments
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
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.
Two elements with no parent, and unhappy linter
JSX Parsing error
I can resolve this error by wrapping the two text components inside a container:
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:
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!