Advertisement
Beginner React, Portals & Fragments

What is a Fragment in React and why would you use one instead of a div?

Short answer

A Fragment lets you group several elements together without adding an extra wrapping element to the actual page. This is useful when adding a div would break your CSS layout, such as inside a table row, or would simply add unnecessary extra markup to the page.

Save React mock interview
Advertisement
AModel answer
A Fragment lets you group several elements together without adding an extra wrapping element to the actual page. This is useful when adding a div would break your CSS layout, such as inside a table row, or would simply add unnecessary extra markup to the page.
function TableRow() {
  return (
    <>
      <td>Name</td>
      <td>Age</td>
    </>
  );
}
Real-world example
A table component avoids breaking its layout by wrapping two table cells in a Fragment instead of a div, since an extra div between table rows and cells would be invalid HTML and break the table's appearance.
Likely follow-ups
  • What is the difference between the short Fragment syntax and writing React.Fragment fully?
  • Can a Fragment accept a key prop when used inside a list?
Related topics