What is the difference between returning React.Fragment or an array?

657 Views Asked by At

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.

1

There are 1 best solutions below

0
Travis James On BEST ANSWER

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