React Fragments

Back to home
Logicmojo - Updated Aug 28, 2021



What do you mean by React fragments?

When using React, you must utilise a render method inside the component to render something on the screen. This render method can return either a single or a group of components. Only one root node will be rendered at a time by the render technique. If you wish to return numerous items, you'll need to use a 'div' tag and place all of your content or elements inside it. Many developers dislike this extra node in the DOM because it occasionally causes incorrect HTML output formatting.
We all know that if we want to render something on the screen, we use the render method inside a component. We can render a single element or several elements, however numerous elements will require a 'div' tag surrounding the content because the render method only renders one root node at a time.


Syntax :

<React.Fragment>  
    <h2> child1 </h2>   
    <p> child2 </p>   
      .. ..... .... ...  
</React.Fragment>




Example :

class App extends React.Component {   
    render() {   
     return (   
       <React.Fragment>  
        <h2> Hello Programmer! </h2>   
        <p> Welcome to the Logicmojo </p>   
       </React.Fragment>  
     );   
    }   
}   



Why we use Fragments?

Because React components may only render one element at a time, it's typical to wrap several elements in a single root element, commonly a div> wrapper.
This workaround works in most circumstances, although it is not always possible to add an extra DOM element.
In our code, React fragments are a better alternative to employing unneeded divs. These fragments don't add any more items to the DOM, therefore the child components of a fragment will render without the need for a wrapping DOM node.
React fragments allow us to arrange numerous sibling components together in the rendered HTML without adding any additional syntax. The following are the main reasons for using the Fragments tag:

🚀 When compared to the div tag, it speeds up code execution.
🚀 It only requires a small amount of RAM.


React fragment vs. div

There's nothing wrong with div containers if they're used to add styles to the JSX. They are not, however, always required to wrap our JSX. When we do so in this situation, they create extra nodes that clog up the DOM tree.
When working with nested components, these wrappers can sometimes produce code anomalies. When using CSS Flexbox and Grid, for example, the div can cause the layout to break. Invalid HTML may also appear for elements that must follow a specified structure, such as ul > li and table>tr>td.
After that, we'll look at some of these problems in practise and see how the React Fragment handles them. Starting with the Flexbox CSS layout.

Shorthand Fragment

For the above procedure, there is another shorthand for defining fragments. Instead of 'React.Fragment,' it appears to be an empty tag where we might use '<>' and " instead.
Note: Because the shorthand syntax does not take key attributes, you must use the React.Fragments> tag instead.


Syntax :

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




Example :

class Temp extends React.Component {   
  render() {   
    return (   
      <>    
        <h2> Hello Programmer! </h2>   
        <p> Welcome to the Logicmojo.. </p>   
         
    );   
  }   
}   



Keyed Fragments

Key attributes are not accepted in the abbreviated syntax. When mapping a collection to an array of fragments, such as when creating a description list, you'll need a key. If you need to specify keys, use the explicit React.Fragment> syntax to declare the fragments.
In some cases, important props must be used in a fragment.
The iteration with the map() method is the focus here. React uses the key prop to determine whether things changed, were removed, or were added when we map elements in React to render a list.
We must also enclose the JSX in a container element whenever we map through items to render multiple JSX.
We wrapped the JSX in a div and assigned the required key prop in the code above. It works good, but let's pretend the div in the DOM tree is redundant and we don't want to render it. As you can expect, we'll need to replace it with a fragment.
However, because it cannot take an attribute, the shorthand notation >/> will not function here. React can be used instead. Fragment or Fragment syntax are two terms for the same thing. For the time being, this syntax only accepts the key prop.
As a result of the key prop being applied to the fragment, our code now looks like this:


Example :

import React from "react";

// ...
const App = () => (
  <>
    <h1>Car name with their model :</h1>
    {items.map(({ car_name, model_name }, index) => (
      <React.Fragment key={index}>
        <p>{car_name}</p>
        <p>{model_name}</p>
      </React.Fragment>
    ))}
  
);
export default App;



Creating and rendering fragments in React

Fragments can be created and rendered in a variety of ways. As illustrated above, you can build a fragment by utilising the Fragment property on the imported React object. You can also use a React component to import a fragment from React and use it in the same way:


Example :

import React, {Fragment} from 'react';

const Child = () => (
  <Fragment>
    <Column>
      <Temp color="#328df6" />
    </Column>
    <Column>
       <Temp color="#f7f7f7" />
    </Column>
  </Fragment>
);



Finally, you may create a React fragment on the fly by wrapping components in an empty HTML element with the shortcut syntax >/>. This is the cleanest and most straightforward approach to handle fragments; it nearly feels like you're working with a standard HTML element:


Example :

const Child = () => (
  <>
    <Column>
      <Temp color="#328df6" />
    </Column>
    <Column>
      <Temp color="#f7f7f7" />
    </Column>
  
);



Conclusion:

Fragments allow you to build code that is cleaner, more readable, and easier to maintain. They're not a replacement for divs in HTML, but they're a better way to structure and render your markup if you're overusing divs.
Using fragments, you may prevent difficulties that disrupt your layouts and possibly reduce the time it takes for your markup to render. You should, however, only utilise them when absolutely necessary. Instead of using a div as a wrapper for your JSX, use a div.