React Fragments allow a component to return multiple sibling elements without adding extra nodes to the DOM.
// Component wrapped with unnecessary div
function UserInfo() {
return (
<div>
<h3>Name: Meghraj</h3>
<p>Role: Developer</p>
</div>
);
}
// Fragment removes extra DOM wrapper
import React from "react";
function UserInfo() {
return (
<React.Fragment>
<h3>Name: Meghraj</h3>
<p>Role: Developer</p>
</React.Fragment>
);
}
export default UserInfo;
// Shorthand fragment syntax
function UserInfo() {
return (
<>
<h3>Name: Meghraj</h3>
<p>Role: Developer</p>
</>
);
}
// Fragment used for multiple table rows
function TableRows() {
return (
<>
<tr><td>John</td></tr>
<tr><td>Jane</td></tr>
</>
);
}
// Keys supported only in React.Fragment
function List() {
const items = ["Apple", "Banana", "Mango"];
return items.map((item, index) => (
<React.Fragment key={index}>
<h4>{item}</h4>
<hr />
</React.Fragment>
));
}
<div> wrappersReact.Fragment