Is Using React fragment is Better than div?

What is react fragment

Fragments basically is a group of a list of children elements without adding extra nodes to the DOM. Let’s see what is an example of react fragment


const FragmentDemo = () =>{
 <h1>Fragment Demo</h1>
 <p>This describes the Fragment Demo Component</p>
  1. We created the FragmentDemo() functional component in the above code.
  2. The component returns a heading using <h1> and we added a simple description using <p> tag.
  3. But when we do this, we got an error at the line closing parenthesis of the return statement like the below image.JSX must have one parent element
  4. It says JSX expression must have one parent element, which means any time your component has to return multiple elements you have to enclose them in a single parent element. So, let’s add the enclosing <div> tag.
    <div> <h1>Fragment Demo</h1> 
    <p>This describes the Fragment Demo Component</p> </div>
  5. Now, the <h1> and <p> elements are contained within enclosing <div>. Then save the file and look at the output:what is react fragment
  6. See the inspect element code, we have enclosed <div> tag included in the DOM tree. So, between the <div> tag from the app component and the <h1> tag in the Fragment Demo component, we have an additional <div> tag. This is well React fragment that comes into the picture.
  7. We can replace the enclosing <div> tag with React fragment and that will prevent the extra node from being added to the DOM. So, the Fragment Demo component replaces the <div> tag with “React.Fragment” as in the below code.
    <h1>Fragment Demo</h1>
    <p>This describes the Fragment Demo Component</p> </React.Fragment>
  8. Now, see inspect element:what is react fragment You can see that we no longer have the <div> app component div tag and the <h1> tag.
READ ALSO  6 key Benefits of Using Styled Components in React


The shorthand syntax of React fragments is instead of <React.Fragment> we can use empty opening <> and closing tag </>. This basically represents the idea that it won’t add an actual element to the DOM. If you use the shorthand syntax, you can’t pass in the “key” attribute.

<h1>Fragment Demo</h1>
<p>This describes the Fragment Demo Component</p>


Leave a Reply