<Fragment> vs <></>

Akash Shyam - Feb 20 '21 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player