What does `<React.Fragment>` do?
React.Fragment is a special wrapper component in React
that lets you group multiple elements without adding an extra node to the DOM.
The problem React.Fragment solves
In React, every component must return a single root element:
function App() {
return (
<h1>Hello</h1>
<p>How are you?</p>
);
}Error:
"Adjacent JSX elements must be wrapped in an enclosing tag."
To fix this, you can wrap the elements in a <div>, but that creates an extra HTML element:
function App() {
return (
<div>
<h1>Hello</h1>
<p>How are you?</p>
</div>
);
}The DOM will contain:
<div>
<h1>Hello</h1>
<p>How are you?</p>
</div>Sometimes that <div> is not needed at all (for example, inside a table, a list, or a grid).
The solution: <React.Fragment>
function App() {
return (
<React.Fragment>
<h1>Hello</h1>
<p>How are you?</p>
</React.Fragment>
);
}Now React groups the elements logically, but does not add a wrapper to the DOM.
As a result, the DOM looks like this:
<h1>Hello</h1>
<p>How are you?</p>Short syntax: <>...</>
The same thing, just shorter:
function App() {
return (
<>
<h1>Hello</h1>
<p>How are you?</p>
</>
);
}This is syntactic sugar for <React.Fragment>.
When it is especially useful
- In tables and lists:
function TableRow() {
return (
<>
<td>Name</td>
<td>Age</td>
</>
);
}Without Fragment you would have to use an extra <tr> or <div>, which breaks the table.
2. When returning multiple elements from map:
const items = ["apple", "banana", "orange"];
return items.map((fruit, i) => (
<React.Fragment key={i}>
<h3>{fruit}</h3>
<hr />
</React.Fragment>
));Here key can only be set with React.Fragment,
since the short syntax <>...</> does not support keys.
Summary
| What it does | Explanation |
|---|---|
| Groups multiple JSX elements | Without adding an extra element to the DOM |
Lets you avoid unnecessary <div> | Especially in tables and lists |
Can have a key | Only the full <React.Fragment key={...}> form |
| Does not render in the DOM | It is an "invisible" wrapper |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.