In React, every component must return a single parent element. Sometimes you just want to group multiple elements without adding an extra <div> (or any other wrapper) to the DOM. This is where Fragments help.
A Fragment lets you wrap multiple JSX elements without creating an additional node in the DOM structure. The UI looks the same, but the HTML stays cleaner and more semantic.
<> ... </> (no attributes allowed).<React.Fragment> ... </React.Fragment> (can use attributes like key).Here, we use a wrapper <div> just to return a single parent. It works, but it adds an unnecessary node to the DOM.
// Component with an extra wrapper div
function Example() {
return (
<div>
<h2>Title</h2>
<p>This adds an unnecessary extra <div>.</p>
</div>
);
}
The rendered HTML will look like:
<div> <h2>Title</h2> <p>This adds an unnecessary extra <div>.</p> </div>
If this component is nested inside another layout, you might end up with many unnecessary <div> tags.
With a Fragment, the JSX still returns a single parent, but that parent does not exist in the DOM.
// Component using a Fragment instead of a div
function Example() {
return (
<>
<h2>Title</h2>
<p>Now we use a Fragment instead of an extra <div>.</p>
</>
);
}
The rendered HTML will now be:
<h2>Title</h2> <p>Now we use a Fragment instead of an extra <div>.</p>
No extra wrapper tag is added — the Fragment is invisible in the DOM, but React is still happy because it got a single parent.
React.Fragment ExplicitlyThe longer form React.Fragment is useful when you need to pass attributes, especially the key prop while rendering lists.
// Using a Fragment to return multiple table rows
function TableRows() {
return (
<>
<tr>
<td>1</td>
<td>Aarav</td>
</tr>
<tr>
<td>2</td>
<td>Maya</td>
</tr>
</>
);
}
// Using React.Fragment explicitly with a key
function Columns() {
return (
<React.Fragment key="col1">
<td>Name</td>
<td>Age</td>
</React.Fragment>
);
}
<tr> or <td> elements without wrapping them in a <div>.<React.Fragment key="..."> lets you attach a key when rendering a list of fragments.<div>.<> cannot have attributes (no key, no className, etc.).<React.Fragment> when you need attributes like key.<>...</> for quick, clean JSX.React.Fragment only when you need a key or other attributes.ProfileInfo that returns your name, age, and city wrapped in a Fragment (use the shorthand <>).UserTable that displays multiple rows using React.Fragment with key props for each row.<div> tags are created around your rows or profile.Goal: Learn how to use Fragments (<> and React.Fragment) to group multiple JSX elements without adding unnecessary DOM nodes, keeping your code and HTML clean and efficient.