Fragments in React
React components can only return one element. Often, too often, I see developers who therefore enclose their component in a div
. But let me just point out the dangers of this.
The problem
Suppose we have two components, one that creates a table row and one that calls the first to create the actual table. The code will then look something like this.
If we now look at the result, we quickly see what went wrong.
In the middle of the table row (tr
) there is now a div
element, which is of course invalid HTML! Fortunately, React has a solution for this: Fragments.
The solution
Fragments are nothing more than elements that are grouping other elements. The difference with a div
is that the former doesn't add extra nodes to the DOM, causing no impact on the HTML itself. If we rewrite the example above with fragments, we get the following:
Note, it is certainly not always wrong to return a div
. You can also ask yourself why we want to "pollute" our DOM with extra HTML nodes if they have no added value.
Also nice to know is that fragments have a short syntax, namely empty tags. You can therefore easily replace it in <>
and <
./
>