Understanding-React-Fragments-Made-Simple

Understanding React Fragments Made Simple: What You Need to Know

In this blog, I will be covering the basics of React Fragments component.
Let’s look at an example to see React Fragments in action.

React v16.2.0 introduced React fragments, a beautiful but basic functionality. Simply knowing about them will help you develop better React components and save you a lot of time when it comes to creating and customizing layouts.

What is the difference between a React fragment and a React component?

Fragments are a syntax for adding several components to a React component without having to wrap them in an additional DOM node.

Let’s take a look at the following code:
const App = () => {
return (
<h1>This is heading1 text</h1>
);
}

export default App

This is a straightforward React component. As was the case above, if only one JSX is returned in a component, we may choose not to wrap it in another wrapper element. When we add more than one JSX element, such as this:

const App = () => {
return (
<h1>This is heading1 text</h1>
<p>This is paragraph text</p>
);
}

export default App

We will encounter a SyntaxError. And thus, crashing our application in development.
In React, when a component returns multiple elements, we must wrap them in a container element like div for the code to work:

const App = () => {
return (
<div>
<h1>This is heading1 text</h1>
<p>This is paragraph text</p>
</div>
);
};
export default App;

While this is fine, it may however cause unintended issues in our components.

Hire ReactJS Developer

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. They add more nodes to the DOM tree when we do this in this case, clogging it up.
These wrappers can result in strange code when used with nested components. The div could ruin the layout, for instance, when using CSS Flexbox and Grid. 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 reality and see how the React Fragment handles them—starting with the Flexbox CSS layout.

Using div wrapper in a CSS layout

Consider the following example to create a simple layout of rows and columns using Flexbox:

import "./styles.css";

const Row = ({ children }) => <div className="row">{children}</div>;

const Column = ({ children }) => <div className="col">{children}</div>;

const Box = ({ color }) => (
<div className="box" style={{ backgroundColor: color }}></div>
);

export default function App() {
return (
<Row>
<Column>
<Box color="#007bff" />
</Column>
<Column>
<Box color="#fc3" />
</Column>
<Column>
<Box color="#ff3333" />
</Column>
</Row>
);
}

Each Row creates a div that encloses information in a single row, whereas a Column creates a vertical enclosing div. Box components are included in every Column. They produce fixed-width containers and backgrounds provided as props:

/* styles.css */
.row {
display: flex;
}
.col {
flex: 1;
}
.box {
min-width: 100px;
min-height: 100px;
}

The above code renders three columns in a single row, as shown below:

three_columns_React_Fragments

See for yourself on CodeSandbox:

Let’s rewrite the code above such that the first two columns are separated into a distinct component named ChildComponent. Consider this a reusable component from which you may choose to decouple:

export default function App() {
return (
<Row>
<ChildComponent />
<Column>
<Box color="#ff3333" />
</Column>
</Row>
);
}

const ChildComponent = () => (
<div>
<Column>
<Box color="#007bff" />
</Column>
<Column>
<Box color="#fc3" />
</Column>
</div>
);

The predicted outcome should be the same as it was previously, but it isn’t. The layout is broken by separating the first two columns into a distinct component, ChildComponent:

first_two_columns_into-a-distinct_component_React fragments

A div wraps all JSX components in the ChildCompoent to group them together. The additional div, on the other hand, creates a layout break since the browser considers it to be part of the layout.
Your browser has no idea that you’ve included the div to prevent an error, and it’s just a wrapper for your enclosing HTML code.
It might be tough to diagnose and determine where the extra nodes are coming from as the component tree becomes deeper. Similarly, if we’re styling and designing our layouts with CSS grids, too many divs might cause the layout to fail.

Why do we use fragments in React?

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 wrapper DOM node.
React fragments allow us to group multiple sibling components together in the rendered HTML without adding any unnecessary markup.
CSS Flexbox layout with fragments
Returning to our code, we can resolve the layout issue by enclosing the component’s JSX in a React fragment rather than a div:

import React from 'react';

const ChildComponent = () => (
<React.Fragment>
<Column>
<Box color="#007bff" />
</Column>
<Column>
<Box color="#fc3" />
</Column>
</React.Fragment>
);

See for yourself on CodeSandbox:

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

import React, {Fragment} from 'react';

const ChildComponent = () => (
<Fragment>
<Column>
<Box color="#007bff" />
</Column>
<Column>
<Box color="#fc3" />
</Column>
</Fragment>
);

Finally, you may build a React fragment on the fly by wrapping components in an empty HTML element using the shortcut syntax >/>. This is the clearest and most straightforward approach to handling fragments; it nearly seems like you’re working with a standard HTML element:

const ChildComponent = () => (
<>
<Column>
<Box color="#007bff" />
</Column>
<Column>
<Box color="#fc3" />
</Column>
</>
);

Using any of the above three methods brings back the original layout because it eliminates the pointless div in the DOM.

Conclusion

Fragments allow you to build code that is clearer, more legible, 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 utilize them when absolutely necessary. Instead of using a div as a wrapper for your JSX, use a div.
Blog Reference :
https://reactjs.org/docs/fragments.html

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply