Questions
This component is breaking layout. Fix it using a React Fragment.
A developer is building a table component. They have a TableRows component that is responsible for rendering a list of <tr> elements.
However, because a React component must return a single root element, they’ve wrapped their <tr> elements in a div. This div is breaking the table’s layout, causing the rows to not align correctly, and also creating invalid semantic HTML, which can impact accessibility.
The Challenge
You’ve been given the TableRows component. Your task is to fix the layout and semantic HTML issue by using a React Fragment to group the <tr> elements without adding an extra node to the DOM.
import React from 'react';
// This component is intended to be used inside a <table>
function TableRows() {
// THE BUG: Wrapping <tr> elements directly in a <div> breaks table semantics.
return (
<div>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</div>
);
}
export default function App() {
return (
<table border="1" style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<TableRows /> {/* This is where the issue manifests */}
</tbody>
</table>
);
} The Solution
function TableRows() { // THE BUG: Wrapping <tr> elements directly in a <div> breaks table semantics. return ( <div> <tr> <td>Row 1, Cell 1</td> <td>Row 1, Cell 2</td> </tr> <tr> <td>Row 2, Cell 1</td> <td>Row 2, Cell 2</td> </tr> </div> ); }
function TableRows() { // FIX: Use a React Fragment (shorthand syntax) to group the <tr> elements. // This allows them to be direct children of <tbody> without an extra DOM node. return ( <> <tr> <td>Row 1, Cell 1</td> <td>Row 1, Cell 2</td> </tr> <tr> <td>Row 2, Cell 1</td> <td>Row 2, Cell 2</td> </tr> </> ); }
Why This Works
React components must return a single root element. This is a fundamental rule of JSX. However, sometimes you need to group multiple elements without introducing an unnecessary div or other wrapper element into the DOM. This is especially true when dealing with semantic HTML structures like tables, lists, or flexbox/grid layouts, where an extra div can break the styling or accessibility.
The Fix: Using React Fragments
React Fragments allow you to group a list of children without adding extra nodes to the DOM. They solve the “single root element” requirement without interfering with your HTML structure.
You can use React.Fragment explicitly or, more commonly, the shorthand syntax <>...</>.
By replacing the div with <>, the <tr> elements are now direct children of <tbody>, which is semantically correct and resolves the layout issues.
Practice Question
What is the primary benefit of using React Fragments?