Rendering and data flow
Group elements with a fragment
Return siblings without adding an unnecessary wrapper element to the DOM.
A React component can only return one single element. When you want to render two siblings, the quick fix is wrapping them in a div. Do that in every component and the page fills with wrapper elements that exist only to satisfy React.
The extra div is not always harmless. Some HTML structures forbid stray elements between their children: a definition list expects dt and dd, a table row expects cells. A wrapper in the wrong place produces invalid HTML, and it can also interfere with CSS layouts built on direct-child selectors, flexbox, or grid.
A Fragment groups sibling elements without adding a DOM wrapper:
function BlogPostExcerpt({ title, description }) {
return (
<>
<h1>{title}</h1>
<p>{description}</p>
</>
)
}
The empty tags <>...</> are the shorthand syntax for a fragment. React receives one return value, while the browser gets h1 and p as direct siblings with nothing around them. Fragments do not appear in the DOM at all.
There is also an explicit form, imported from React. Older codebases write React.Fragment, which is the same component. Use the shorthand by default.
The explicit form earns its keep in one common case: when the group needs a key. This happens when a list renders pairs of elements, like the name and role rows of a definition list:
import { Fragment } from 'react'
function PeopleList({ people }) {
return (
<dl>
{people.map(person => (
<Fragment key={person.id}>
<dt>{person.name}</dt>
<dd>{person.role}</dd>
</Fragment>
))}
</dl>
)
}
The short <>...</> syntax cannot receive a key or any other attribute, so this is where you spell out Fragment.
One caution before you replace every wrapper. Do not use a fragment when a semantic wrapper would improve the document. A group that forms a section may need section; navigation may need nav. The fragment is for groups that need no element of their own, not a way to avoid thinking about HTML structure.
Inspect the DOM with and without a div wrapper. Choose the version that preserves the intended HTML structure.
Lesson completed