Fragment
In React, a Fragment
is a lightweight container used to group multiple elements without adding an extra node to the DOM. Normally, when you return multiple elements from a component, you have to wrap them in a parent element like a div
. However, this can lead to unnecessary nesting in the DOM, which can affect performance and styling. Fragments help you avoid this issue.
Why Use Fragments?
Less DOM Clutter: Using a
div
or another HTML element to wrap your component output can introduce unnecessary parent nodes into the DOM, which can affect both performance and styling.Simpler JSX: Fragments make your JSX look cleaner and more readable by eliminating the need for wrapper
divs
.Table Rows and Other Edge Cases: Some HTML structures, like tables, have strict child-parent relationships that make it difficult to wrap child elements in a
div
. Fragments solve this problem.
Syntax
There are two syntaxes for Fragments:
Short Syntax: This is the most common and concise way to create a Fragment. It looks like empty tags.
<>
<ChildA />
<ChildB />
<ChildC />
</>Explicit Syntax: This involves using
React.Fragment
to declare a Fragment. This is useful when you need to pass akey
prop for items in a list.<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>With a
key
prop:<React.Fragment key={someKey}>
<ChildA />
<ChildB />
</React.Fragment>
Example
Without Fragment:
function App() {
return (
<div>
<Header />
<Main />
<Footer />
</div>
);
}
With Fragment:
function App() {
return (
<>
<Header />
<Main />
<Footer />
</>
);
}
In the second example, the App
component returns the same elements, but without the wrapping div
. This makes the DOM lighter and cleaner.
Fragments are a useful feature in React that allow you to keep your DOM structure clean and efficient. They are particularly helpful in scenarios where adding a wrapper element could mess up your layout or styling.