Don't return a React.Fragment from your reusable components
Why good reusable components make no assumptions about where they're being rendered.
It is sometimes tempting to create reusable components that look like this
function BlogPost() {
return (
<>
<Heading />
<Preamble />
<Body />
<RelatedPosts />
</>
)
}
which you render like this
function SomeComponent() {
return (
<article>
<BlogPost />
</article>
)
}
You check the UI and it looks good, so you call it a day.
But there's a problem. What if you render a <BlogPost /> somewhere else? The layout of <BlogPost /> is now dependent on where it's being rendered.
If we were to render it inside a parent container that looks like this instead
function SomeOtherComponent() {
return (
<div style={{display: "flex", flexDirection: "row"}}>
<BlogPost />
</div>
)
}
... suddenly our UI is messed up, with everything laid out horizontally instead of vertically as originally intended.
Do this instead, and your component will look the same wherever it's used.
function BlogPost() {
return (
<article>
<Heading />
<Preamble />
<Body />
<RelatedPosts />
</article>
)
}
Unless you're 100% sure your component will only be used in that one place, don't return a React.Fragment.