When to use <React.fragment /> vs <>
In a previous post I reviewed when you should use a fragment instead of a standard HTML element when building React applications. In this post I want to review when you should use the longhand <React.Fragment>
instead of the shorthand version <>
.
- Use
<React.Fragment>
for when you need to map over a collection of fragments.
function Listicle(props) {
const {items} = props
return (
<dl>
{items.map(item => (
<React.Fragment key={item.id}>
<dt>{item.name}</dt>
<dt>{item.content}</dt>
</React.Fragment>
))}
</dl>
);
}
- Use the shorthand
<>
any other time.