
Fragments, <> </>
are a way of wrapping a group of other elements within a React app, without creating an unnecessary <div>
element.
React requires that every component returns one, and only one, ‘parent’ JSX element like so. Because of this react rule, HTML-like elements, such as <div>
are often used to wrap other elements within the JSX of our return; but these extra div’s that are created, aren’t always useful or necessary:


In the examples above, the div in the ChildComponent doesn’t have any purpose other than to wrap our <p>
element, and when rendered ends up creating a nested div within the ParentComponent’s div, like so:
<div className="parent">
<div>
<p>Heya! I'm a child component!</p>
<p> My name is kiddo! </p>
</div>
<div>
<p>Heya! I'm a child component!</p>
<p> My name is kiddo! </p>
</div>
</div>
Now, these nested div’s don’t have any purpose within this block of code, and they don’t have any styling except for the default properties for our application; in other words, they aren’t really necessary. But wait! Without them, our ChildComponent wouldn’t render because it would be returning more than one ‘parent’ JSX element.
So how can we solve this conundrum?
We can solve it with fragments!!
Fragments allow a component to return multiple elements without creating an additional wrapper (div) element in the DOM. With fragments we can refactor our original ChildComponent as follows:

With our reformatted ChildComponent, our DOM will now return this instead:
<div className="parent">
<p>Heya! I'm a child component!</p>
<p> My name is kiddo! </p>
<p>Heya! I'm a child component!</p>
<p> My name is kiddo! </p>
</div>
Isn’t this much cleaner and easier to read? I think so!
Now, you may also see <React.Fragment> </React.Fragment>
. This is another way of writing fragments and can be used interchangeably with the shorthand <> </>
.
Go forth and enjoy your simplified fragmented components!