Fragments
Fragments
A common pattern in React is for a component to return multiple elements. However, JSX syntax rules dictate that a component can only return a single root element.
To satisfy this rule, developers historically wrapped their elements in a generic <div>:
// Returning a wrapping div just to satisfy JSX rules
function Columns() {
return (
<div>
<td>Hello</td>
<td>World</td>
</div>
);
}
The problem with the above code is that it creates an unnecessary <div> in the actual HTML DOM. This can break CSS layouts (like Flexbox or Grid) and generate invalid HTML (e.g., a <div> is not allowed directly inside a <tr>).
React Fragments
Fragments let you group a list of children without adding extra nodes to the DOM.
import { Fragment } from 'react';
function Columns() {
return (
<Fragment>
<td>Hello</td>
<td>World</td>
</Fragment>
);
}
When React renders <Columns />, the <Fragment> wrapper completely disappears, leaving only the <td> tags in the DOM.
Short Syntax (<>...</>)
React provides a much shorter syntax for declaring fragments, which looks like empty tags:
function Columns() {
return (
<>
<td>Hello</td>
<td>World</td>
</>
);
}
This is the most common way to write Fragments in modern React codebases.
Keyed Fragments
There is one limitation to the <>...</> short syntax: it cannot accept attributes or keys.
If you are rendering a list of fragments using .map(), you need to provide a key prop to help React identify each item. In this specific scenario, you must use the explicit <Fragment> (or <React.Fragment>) syntax.
function Glossary(props) {
return (
<dl>
{props.items.map(item => (
// Without the 'key', React will throw a warning
// The short syntax <key={item.id}> is invalid!
<Fragment key={item.id}>
<dt>{item.term}</dt>
<dd>{item.description}</dd>
</Fragment>
))}
</dl>
);
}
Interview Questions
Q: Why do we need Fragments (<></>) in React?
A: JSX expressions must compile into a single parent React.createElement() call. If you want to return multiple sibling elements, you must wrap them. Fragments allow you to group sibling elements without adding an unnecessary <div> or wrapper node to the actual DOM, which keeps the HTML clean and preserves CSS grid/flexbox layouts.
Q: When would you explicitly use <React.Fragment> instead of the shorthand <></> syntax?
A: The shorthand <></> syntax does not support attributes. If you are rendering a list of fragments inside a .map() loop, you are required to provide a key prop. In this scenario, you must use <React.Fragment key={id}>.