Appearance
Fragment
React Fragment: <Fragment> or <> is a useful syntax to group elements / components together without adding HTML nodes.
For example:
js
function Example() {
return (
<Fragment>
<h1>Header</h1>
<p>Body</p>
</Fragment>
)
}The above will render to html without an additional wrapping <div>:
html
<h1>Header</h1>
<p>Body</p>The shorthand syntax is <></>:
js
function Example() {
return (
<>
<h1>Header</h1>
<p>Body</p>
</>
)
}Note if you need to use key prop e.g. in a list, you must use the full <Fragment> syntax:
js
function List({ items }) {
return items.map((item) => {
<key={item.id}> // ❌ invalid syntax
<h2>{item.title}</h2>
<p>{item.description}</p>
</>
})
}
function List({ items }) {
return items.map((item) => {
<Fragment key={item.id}> // ✅ valid syntax
<h2>{item.title}</h2>
<p>{item.description}</p>
</Fragment>
})
}