React Basics
React Fragments
A fragment lets a component return several sibling elements without adding a wrapper node to the DOM. Write it either as the shorthand <>…</> or the explicit <React.Fragment>…</React.Fragment> when you need to pass a key.
What is Fragments in React?
A fragment lets a component return several sibling elements without adding a wrapper node to the DOM. Write it either as the shorthand <>…</> or the explicit <React.Fragment>…</React.Fragment> when you need to pass a key.
Why Fragments matters
Wrapper divs quietly break CSS layouts. A stray div between a flex or grid container and its intended children stops the layout rules from applying, and in tables an extra div is invalid HTML altogether.
Fragments example
function Columns() {
return (
<>
<td>Name</td>
<td>Stipend</td>
</>
);
}
// <tr><Columns /></tr> renders valid HTML — no wrapper div.How this works
A div here would produce <tr><div><td>…</td></div></tr>, which browsers reject and reflow unpredictably. The fragment groups the cells for JavaScript purposes and disappears at render time.
Keyed fragments in a list
import { Fragment } from 'react';
function Glossary({ items }) {
return (
<dl>
{items.map(item => (
<Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.definition}</dd>
</Fragment>
))}
</dl>
);
}The shorthand <>…</> cannot take props, so when each group in a list needs a key you must use the long form imported from react.
Key points to remember
- Fragments render nothing to the DOM — the children appear as direct siblings.
- Use the shorthand everywhere except when a key is required.
- They are essential inside tables, flex containers, grid containers and definition lists.
Common mistakes with Fragments
- Trying to put key on the <> shorthand — it is a syntax error.
- Adding a wrapper div "just to be safe" inside grid and flex layouts, which silently breaks the layout.
React Fragments— Interview Questions & FAQs
What is the difference between a fragment and a div?+
A div creates a real DOM node that participates in layout, styling and CSS selectors. A fragment creates nothing — its children become direct siblings in the parent element.
