In React, a common pattern is to render multiple elements within a component. However, wrapping these elements in a traditional <div>
can introduce unnecessary DOM nodes and affect the structure of the rendered output. React provides a solution to this problem through the use of React Fragment.
React Fragment is a built-in component that allows developers to group multiple elements without adding extra nodes to the DOM. It provides a cleaner syntax for composing components and rendering multiple elements within a single parent container.
When using React Fragment, it allows a group of elements to be rendered without introducing a wrapping <div>
or any other DOM node. This helps maintain a cleaner DOM structure and improves performance.
Fragments allow grouping multiple elements without adding extra nodes to the DOM. Here's an example:
const Index = () => {
return (
<React.Fragment>
<div className="container">
<h1 className="title">React App</h1>
<p>Lorem ipsum dolor, sit amet consectetur elit.</p>
</div>
</React.Fragment>
);
};
Developers can use Fragments or the shorthand syntax or React.Fragment
(<>...</>
) (or simply <></>
) to achieve the same result. Here's an example:
const Index = () => {
return (
<>
<div className="container">
<h1 className="title">React App</h1>
<p>Lorem ipsum dolor, sit amet consectetur elit.</p>
</div>
</>
);
};
In this examples, we use a fragment (<>...</>
) or React Fragments (<React.Fragment>...</React.Fragment>
) to enclose multiple elements, including a <div>
with a class name container
, an <h1>
element, and a <p>
element.
Both React.Fragment
and Fragments (<>...</>
) approaches allow you to group multiple elements within JSX without introducing unnecessary DOM nodes, ensuring a cleaner and more efficient rendering process.
When you use React.Fragment, you can also add attributes to the fragment, but these attributes will not be added to any DOM node. However, when you use the shorthand syntax <></>
, you cannot add attributes.