React Fragments & Clean DOMs
A common pattern in React is for a component to return multiple elements. Since JavaScript functions cannot return multiple values independently, React requires you to wrap them. Enter React Fragments.
The Problem: Div Soup
Often, developers wrap adjacent JSX elements in a <div>. While this solves the React compiler error, it litters your actual HTML DOM with unnecessary wrappers. We call this "Div Soup." Overusing divs can accidentally break carefully crafted CSS Grid or Flexbox layouts by inserting unexpected parent containers between the flex container and its intended flex children.
React.Fragment
<React.Fragment> is a built-in React component that lets you group a list of children without adding an extra node to the DOM. When React renders the component, the Fragment disappears, leaving only your inner elements in the HTML output.
Short Syntax
Typing <React.Fragment> over and over gets tedious. React offers an elegant short syntax using empty tags: <>...</>. In 99% of cases, you should use the short syntax to keep your JSX clean and readable.
Keys and Loops
The only time you cannot use the short syntax is when you are mapping over an array and need to pass a key prop. The short syntax does not support attributes or props. If you need a key, you must use the explicit <React.Fragment key={id}> syntax.
View Full Transcript+
This section contains the full detailed transcript covering why JSX requires a single parent element (because it transpiles to React.createElement, which returns a single object), the performance impact of Deep DOM trees, and alternative ways to return arrays of elements from components prior to React 16.
