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

Tomasz Łakomy
InstructorTomasz Łakomy
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 5 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.

egghead
egghead
~ 27 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today