In this tutorial, you will learn about React fragments and why they are useful. When writing mark-up within ReactJS instead of working with HTML directly we work with JSX. When all your React components are compiled all the JSX is converted into Javascript functions. Converting mark-up to Javascript has some good points and some bad points. One limitation of JavaScript functions is that you cannot return multiple expressions. This means that when returning JSX from a render method, the JSX has to be nested into a single root node otherwise invalid Javascript would be generated. This return would be invalid:
To get around this issue, many developers simply returned all mark-up wrapped in an enclosing div
tag, like so:
Adding extra JSX elements just to make the compiler happy is sub-optimal. First, adding unused elements onto a page degrades performance marginally. In large applications, this can result in a lot of needed div
tags being rendered. Second, adding the extra divs might affect other elements on the page. I have worked on a system where unexpected div
has resulted in strange odds. This does not happen very frequently, however, it can happen.
A cool thing happened when ReactJS v16.2 was released, fragments. Fragments were introduced to get around this previous limitation. Instead of having to return a div
element just to keep the compiler happy, a fragment can be returned instead:
React Fragment also provides a much cleaner and simpler syntactic sugar form, <>
. The snippet above can be further simplified like this:
Finally, another less clean alternative is to return a single array of elements, separated by a comma, like this:
This will have the same effect as using a fragment, however, the code is much harder to read quickly in my opinion. If you are not using React Fragments then you definitely should. You can learn more about them here. Happy Coding 🤘