React: <React.Fragment> vs array
Official document says
Using array notation has has some confusing differences from normal JSX:
Children in an array must be separated by commas.
Children in an array must have a key to prevent React’s key warning.
Strings must be wrapped in quotes.
So to make it simple, React provides Fragment component that can be used in place of arrays.
Consider how we can wrap multiple children using array
render() {
return [
"Some text.",
<h2 key="heading-1">A heading</h2>,
"More text.",
<h2 key="heading-2">Another heading</h2>,
"Even more text."
];
}
And how it can be achieved using Fragments.
render() {
return (
<Fragment>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</Fragment>
);
}
Taken directly from official document.
Fragments can be written as below aswell.
render() {
return (
<>
Some text.
<h2>A heading</h2>
More text.
<h2>Another heading</h2>
Even more text.
</>
);
}
There are two major advantages of using Fragments over array in return statement
- Simplistic syntax similar to Other components so that you don't have to worry about return comma separated values, wrapping strings in quotes etc
- Fragments can take attribute such as key which is often important when you are returning data from within map. You can't do that using an array.
Example
const ReturnFragments = () => {
const items = list.map((item) => {
<React.Fragment key={item.id}>
<div key={1}>Item 1</div>
<div key={2}>Item 2</div>
<div key={3}>Item 3</div>
</React.Fragment>
})
return items
}