DEV Community

Shivraj gurjar
Shivraj gurjar

Posted on • Updated on

Fragment tag in React

Image description

React Fragments: A Cleaner Way to Group Elements

In React, when you want to return multiple elements from a component, you typically need to wrap them in a single parent element. This is because React enforces a rule that each component can only render a single parent element. While this makes sense from a structural perspective, it can lead to unnecessary wrapper elements in the rendered HTML, which can affect the page's layout and styling.

This is where React Fragments come to the rescue. A React Fragment is a lightweight way to group multiple elements without adding extra nodes to the DOM. They allow you to group elements together without introducing a new parent element in the HTML output.

Before Fragment

// Rendering with div tag  
  class App extends React.Component {   
       render() {    
        return (   
           //Extraneous div element   
           <div>  
             <h2> Hello World! </h2>   
             <p> Welcome to the Shiv's Blog. </p>   
           </div>   
        );   
       }   
  }
Enter fullscreen mode Exit fullscreen mode

To solve this problem, React introduced Fragment from 16.2 and above version. Fragments allows you to group a list of children without adding extra node to DOM.

syntax

<React.Fragment>  
  <h2> child1 </h2>   
  <p> child2 </p>   
  .. ..... .... ...  
</React.Fragment>
Enter fullscreen mode Exit fullscreen mode

Example 1

// Rendering with fragments tag  
  class App extends React.Component {   
      render() {   
       return (   
         <React.Fragment>  
              <h2> Hello World! </h2>   
              <p> Welcome to the Shiv's Blog. </p>   
           </React.Fragment>  
       );   
      }   
  }
Enter fullscreen mode Exit fullscreen mode

Keyed Fragments

This shorthand syntax does not accept key attributes. You need a key for mapping a collection to an array of fragments such as to create a description list. If you need to provide a keys, you have to declare the Fragments with the explicit syntax.

Function  = (props) {  
    return (  
      <Fragment>  
        {props.items.data.map(item => (  
          // Without the 'key', React will give a key warning  
          <React.Fragment key={item.id}>  
            <h2>{item.name}</h2>  
            <p>{item.url}</p>  
            <p>{item.description}</p>  
          </React.Fragment>  
        ))}  
      </Fragment>  
    )  
  }
Enter fullscreen mode Exit fullscreen mode

The Avengers and React Fragments: A Web Development Saga

In a parallel digital universe, the Avengers decided to venture into the world of web development. Each Avenger was assigned a web development task to save the day, and they soon discovered the power of React Fragments.

Iron Man's Dilemma:

Tony Stark, also known as Iron Man, was tasked with creating a superhero team display on the Avengers' website. He had to list the team members, their images, and a brief description. However, Iron Man was a perfectionist. He didn't want any unnecessary HTML elements cluttering up the web page.

At first, he wrote his code like this:

function AvengersTeam() {
  return (
    <div className="team">
      <div className="hero">
        <img src="ironman.jpg" alt="Iron Man" />
        <h2>Iron Man</h2>
        <p>Tony Stark, the genius billionaire.</p>
      </div>
      <div className="hero">
        <img src="captainamerica.jpg" alt="Captain America" />
        <h2>Captain America</h2>
        <p>Steve Rogers, the super-soldier.</p>
      </div>
      {/* More heroes here */}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Iron Man felt that these extra

elements were like unnecessary bulky armor. He wanted a sleeker solution.

Enter React Fragments:

One day, while tinkering in his lab, Iron Man had a breakthrough. He discovered React Fragments, a tool that would help him achieve his goal of cleaner code.

With React Fragments, Iron Man transformed his code into a more elegant and efficient form:

function AvengersTeam() {
  return (
    <>
      <div className="hero">
        <img src="ironman.jpg" alt="Iron Man" />
        <h2>Iron Man</h2>
        <p>Tony Stark, the genius billionaire.</p>
      </div>
      <div className="hero">
        <img src="captainamerica.jpg" alt="Captain America" />
        <h2>Captain America</h2>
        <p>Steve Rogers, the super-soldier.</p>
      </div>
      {/* More heroes here */}
    </>
  );
}

With React Fragments, Iron Man's code became streamlined, just like his Iron Man suit. There were no unnecessary wrapper elements, and the website loaded faster, just in time to save the world from poorly structured HTML.

Top comments (0)