In React JS, we often encounter situations where we need to return multiple elements from a function component. However, React requires that a single component returns exactly one root element. This is where JSX Fragments come in handy!
JSX Fragments are React components that do not have a separate render method or a name. They are used to group multiple children without adding an extra node to the DOM.
In simple terms, they allow us to group multiple elements without creating unnecessary wrappers.
You can create a Fragment by using the <React.Fragment> syntax. However, for a cleaner syntax, React 16.2 and later versions introduced the shorter <> ... </> syntax.
import React from 'react';
function MyComponent() {
return (
<>
<h1>Hello</h1>
<h2>World</h2>
</>
);
}In the above example, we've created a simple component that returns a fragment containing two headings. The fragment acts as a container, allowing us to group these two elements without introducing an extra DOM node.
Let's consider a real-world example where we have a list of items, and we want to render each item inside a <li> element.
import React from 'react';
function ListItems({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}Here, we are rendering each item inside a <li> tag. However, if our items array contains multiple items, we'll end up with multiple <li> tags as direct children of the <ul> tag. This is not ideal, as it creates extra DOM nodes unnecessarily.
To solve this issue, we can use a fragment to wrap the <li> elements, ensuring that only one root element is returned.
import React from 'react';
function ListItems({ items }) {
return (
<>
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</>
);
}Now, our component returns a cleaner structure, with the fragment acting as a container for the <li> elements.
What is the purpose of JSX Fragments in React JS?