ReactJS | Fragments

We know that we make use of render method inside a component whenever we want to render something to the screen. We may render a single element or multiple elements, though rendering multiple elements will require a ‘div’ tag around the content as the render method will only render a single root node inside it at a time.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// simple rendering with div
class Columns extends React.Component {
  render() {
    return (
      <div> // extraneous div element
        <h2>Hello</h2>
        <p>How you doin'?</p>
      </div>
    );
  }
}

chevron_right


As we saw in the above code when we are trying to render more than one root element we have to put the entire content inside the ‘div’ tag which is not loved by many developers. So in React 16.2 version, Fragments were introduced and we use them instead of the extraneous ‘div’ tag.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// simple rendering with fragments
class Columns extends React.Component {
  render() {
    return (
      <React.Fragment> 
        <h2>Hello</h2>
        <p>How you doin'?</p>
      </React.Fragment>
    );
  }
}

chevron_right


The output of the previous code and the code above is same but the main reason of using is that it is a tiny bit faster as when compared to the one with the ‘div’ tag inside it, as we didn’t create any DOM node. Also, it takes less memory. Another shorthand also exists for the above method in which we make use of ‘<>’ and ‘</>’ instead of the ‘React.Fragment’.
Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// simple rendering with short syntax
class Columns extends React.Component {
  render() {
    return (
      <> 
        <h2>Hello</h2>
        <p>How you doin'?</p>
      </>
    );
  }
}

chevron_right




My Personal Notes arrow_drop_up

Executive Software Developer at Cavisson Systems

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.