Use React Fragments to wrap adjacent JSX elements without adding unnecessary wrappers

Tomasz Łakomy
InstructorTomasz Łakomy

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 4 years ago

In this lesson, we are going to use React Fragments to wrap adjacent JSX elements without introducing unnecessary wrapper elements to DOM.

Before Fragments came along, the popular pattern was to wrap enclosing elements inside of <div> tags which didn't serve any purpose apart from being a wrapper. This can lead to a huge DOM structure which may be difficult to navigate in devtools and may also lead to some performance issues if our app is large. This lesson will show a better approach to dealing with that problem.

Instructor: [00:00] We start with a very simple component which renders a single div element. It's visible over here. Imagine if I wanted to have more of those, for instance, five boxes saying "Hello." After we save it, refresh it, we get an issue. The issue is that React expects JSX elements to be wrapped in an enclosing tag.

[00:24] There's an easy way to fix this, which is wrapping those divs inside of another div. It's going to work just fine, but there's a problem with that. The problem is that we are introducing additional divs only because we need to wrap those divs in something. It gets worse after we do this button over and over again.

[00:46] There's a way we can fix this. To fix this, import Fragment from react. We can change this enclosing div to a Fragment. It works exactly the same. The difference is that if we check in DevTools, we're going to see that those boxes are not wrapped inside of an any element.

[01:07] There's also another syntax which allows us to achieve exactly the same goal. We can remove this Fragment import and replace those fragments with an empty HTML element. It's going to work exactly the same. We have those boxes without any HTML element wrapping them.