How to replace div tag placed by component in Reactjs


Sometime you may notice that component that return multiple HTML element have a div container which wrap the Children.

In some cases we need not place an additional div. So what we do ?


A Fragment is come to fill this space. It is an advanced feature and can used with render or return statements of component . The parent div can be simply replaced by <React.Fragment.>

Component with div

Here is regular component look like

function RegularComponent() {
   return (
       <Div>
           <h1>React Component</h1>
           <tt>I am a Component</tt>
       <Div>
  )
}

In the picture you can see the highlighted portion of the div , which is placed by the above component

Fragmented component

Here is the Fragment version of the component function. In the highlighted portion you can see that the additional  div tag removed by the fragment.

function RegularComponent() {
   return (
       <React.Fragment>
           <h1>React Component</h1>
           <tt>I am a Component</tt>
       </React.Fragment>
  )
}

In the developer tool element of your browser, the additional div is go away.

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.