The root element problem
Remember a JSX rule: a component must return a single root element. If you try to return two sibling elements, it errors:
// ❌ Error: two root elements
function Data() {
return (
<h1>Title</h1>
<p>Description</p>
);
}
The classic solution is to wrap them in a <div>. But sometimes that extra <div>
gets in the way: it clutters the HTML, can break layouts with CSS (flex, grid, tables)
or add unnecessary nodes to the tree.
The solution: fragments
A fragment groups several elements without creating an extra node in the DOM. It is
written with the short syntax <>...</>:
function Data() {
return (
<>
<h1>Title</h1>
<p>Description</p>
</>
);
}
This renders the <h1> and the <p> as direct siblings, without any
<div> wrapping them. In the browser you will not see any additional container.
Fragments with key in lists
The short form <>...</> does not accept props. When you need a fragment with
key (for example, inside a .map() that returns several elements per
row), use the long form <React.Fragment>:
{items.map((item) => (
<React.Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.definition}</dd>
</React.Fragment>
))}
Rule of thumb: use
<>...</>by default; switch to<React.Fragment key={...}>only when you need to pass it akey.