1

Is there any difference between returning React.Fragment

function Foo(){
    return (
        <>
            <div>hey</div>
            <div>hey</div>
        </>
    )
}

Or return an array of components

function Bar(){
    return (
        [
            <div>hey</div>,
            <div>hey</div>,
        ]
    )
}

?

Here is a codesandbox for example.

Vencovsky
  • 28,550
  • 17
  • 109
  • 176
  • @YevgenGorbunkov [This codesandbox](https://codesandbox.io/s/kind-bassi-uu2t2) says you are wrong. The second function does return a valid React Component. – Vencovsky Jan 15 '20 at 14:24
  • "A React component can also return an array of elements:" https://reactjs.org/docs/jsx-in-depth.html#jsx-children – Will Jan 15 '20 at 14:25
  • @YevgenGorbunkov as of React v16+ that's no longer true – James Jan 15 '20 at 14:27
  • 3
    Does this answer your question? [React: vs array](https://stackoverflow.com/questions/55236346/react-react-fragment-vs-array) – Ali Mousavi Jan 15 '20 at 14:30

1 Answers1

3

From the React documentation: https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html

Using array notation 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, if you wanted to use your second example you would need to give each item a key prop, and you have to make sure to comma seperate your list of items if you use an array.

So, Fragments just give a more familiar syntax vs arrays

Travis James
  • 1,879
  • 9
  • 22