Skip to content
Related Articles

Related Articles

ReactJS Fragments
  • Last Updated : 04 Feb, 2021

We know that we make use of the 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: Create a React app and edit the App.js file from the src folder as:

Filename- App.js:

javascript




import React from "react";
  
// Simple rendering with div
class App extends React.Component {
  render() {
    return (
      // Extraneous div element
      <div>
        <h2>Hello</h2>
  
        <p>How you doin'?</p>
      </div>
    );
  }
}
  
export default App;

Output:



Reason to use Fragments: 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. 

Syntax:

<React.Fragment>  
      <h2>Child-1</h2>   
      <p> Child-2</p>   
</React.Fragment>  

Example: Open App.js and replace the code with the below code.

javascript




import React from "react";
  
// Simple rendering with fragment syntax
class App extends React.Component {
  render() {
    return (
      <React.Fragment>
        <h2>Hello</h2>
  
        <p>How you doin'?</p>
      </React.Fragment>
    );
  }
}
  
export default App;

Output:

Shorthand Fragment: The output of the first code and the code above is the same but the main reason for using is that it is a tiny bit faster 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’. 

Note: The shorthand syntax does not accept key attributes in that case you have to use the <React.Fragments> tag.
Syntax:

<>  
      <h2>Child-1</h2>   
      <p> Child-2</p>   
</> 

Example: Open App.js and replace the code with the below code.

javascript




import React from "react";
  
// Simple rendering with short syntax
class App extends React.Component {
  render() {
    return (
      <>
        <h2>Hello</h2>
  
        <p>How you doin'?</p>
      </>
    );
  }
}
  
export default App;

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :