← React Beginner Questions - Set 2 Q16
React Beginner Questions - Set 2
A component must return one node — but that node does not have to be an element. A fragment groups children without adding a wrapper to the DOM.
// With a wrapper div: an extra level in the DOM, and flex/grid
// layouts get a new child they did not ask for.
function BadRow() {
return (
<div>
<td>Name</td>
<td>Price</td>
</div>
);
}
// With a fragment: same JSX, no extra node
function GoodRow() {
return (
<>
<td>Name</td>
<td>Price</td>
</>
);
}
// Keyed fragment, needed when returning a list of groups
import { Fragment } from 'react';
const groups = rows.map(g => (
<Fragment key={g.id}>
{g.items.map(i => <li key={i.id}>{i.label}</li>)}
</Fragment>
));