DEV Community

Akash Shyam
Akash Shyam

Posted on • Updated on

<Fragment> vs <></>

Introduction

Hey Guys 👋, hope you're having a great weekend. Today, I'm going to speak about the pros and cons of and <>. I'll also compare them and give you my opinion on what should be used.

What is a Fragment

In jsx, we are not allowed to return more than 1 child element. For example -

Allowed -

function myDemo() {
   return <p>Demo</p>
}
Enter fullscreen mode Exit fullscreen mode

Not allowed

function myDemo() {
   return (
      <p>Demo</p>
      <p>Bad code</p>
   )
}
Enter fullscreen mode Exit fullscreen mode

So, what used to happen was that developers used to put in a div surrounding the adjacent elements -

function myDemo() {
   return (
      <div>
          <p>Demo</p>
          <p>Bad code</p>
      </div>
   )
}
Enter fullscreen mode Exit fullscreen mode

This approach of adding a div added an extra element into the DOM and sometime messed up the styling. So, there was a feature in react called React.Fragment. It was used like this -

function myDemo() {
   return (
      <React.Fragment>
          <p>Demo</p>
          <p>Bad code</p>
      </React.Fragment>
   )
}
Enter fullscreen mode Exit fullscreen mode

React.Fragment acted as a parent element for the adjacent JSX elements however it was not added into the DOM.

In react 16.2, <></> was introduced.<></> is basically an empty JSX element that does the same functionality

The Comparison

According to me, React.Fragment is much clearer and it's obvious that it acts as a fragment. On the other hand, <></> may seem like a bug to beginners who are not aware of React.Fragment

That's all for now, hope you guys liked the post. Share your views in the comments.

Top comments (3)

Collapse
 
jackmellis profile image
Jack

<> is shorter, doesnt require a specific import, and is no harder to explain to a new developer than the fragment component.

That's why I prefer it, but in the grand scheme of things it really doesnt matter as long as you're consistent right?

Collapse
 
akashshyam profile image
Akash Shyam

Exactly, use the same thing across the whole codebase

Collapse
 
prog profile image
prog

you can't add properties like key with <></> syntax