Kayla Budzeak
2 min readMay 28, 2021
What the <>! What are fragments?

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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Kayla Budzeak
Kayla Budzeak

Written by Kayla Budzeak

I'm a Full-Stack Software Engineer, with a background in customer service, who recently graduated from Flatiron School. In my down time I love to bake & garden.

No responses yet

Write a response