Fragments in React — React Technical Interview Questions & Answers
Fragments in React
Fragments in React
- A fragment groups children without adding a DOM node. <> <h1/> <p/> </> is the short form. When you map and need a key, use <Fragment key={id}> — the short <> cannot take attributes.
- Why bother: wrapping table cells in a div is invalid HTML. Fragment keeps <td> siblings legal. Don’t Fragment everything ‘for purity’ — a div is fine when you actually need a layout box.
- Fragments in React — two cells, no extra wrapper in the DOM. Short <> cannot take a key — use Fragment.
Technical Interview Tip: <> vs Fragment+key.
Code Examples for Fragments in React
Example
// Fragment
import { Fragment } from "react";
export default function Cells({ rows }) {
return rows.map((r) => (
<Fragment key={r.id}>
<td>{r.name}</td>
<td>{r.marks}</td>
</Fragment>
));
}
Fragments in React — two cells, no extra wrapper in the DOM. Short <> cannot take a key — use Fragment.
How to Explain Fragments in React to an Interviewer
Explain Fragments as if you are teaching a junior — definition, then one tiny UI.
Group without extra DOM node. <Fragment key>, not <>.
Write 5–10 lines that use Fragments and say what the UI does.
Show JSX Say the screen
What mistake do freshers make with Fragments?
table cells / multiple roots.