What are React Fragments used for?
React fragments are a special feature in React that let you write group children elements or components without creating an actual node in the DOM.
The fragment syntax looks like an empty set of tags <></>
or are tags labeled React.Fragment.
In simpler terms, sometimes we need to put multiple React elements under a single parent, but we don't want to use a generic HTML element like a div
.
If you are writing a table, for example, this would be invalid HTML:
function Table() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
function Columns() {
return (
<div>
<td>Column 1</td>
<td>Column 2</td>
</div>
);
}
We could avoid this problem by using a fragment instead of a div
element in our Columns
component.
function Columns() {
return (
<>
<td>Column 1</td>
<td>Column 2</td>
</>
);
}
Another reason for choosing a fragment is that sometimes adding an additional HTML element may change the way our CSS styles are applied.