"A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM".
The first elementary steps you have to take while learning React. - if you need to return multiple elements you need to wrap them with React.Fragment (1).
const SomeComponent = () => { return ( <React.Fragment> <FirstElement/> <SecondElement/> </React.Fragment> ) }
It's pretty obvious, but have you ever thought why can't we just return two elements?
- Yes? Good for you! Unfortunately, I only found out the answer during the Kent C. Dodds epicreact course (almost a year after I first started using React!) (2).
const SomeComponent = () => { return ( <FirstElement/> <SecondElement/> ) }
This code won't work and we will end up with the error "JSX expression must have one parent element". But why? Is it some weird React thing that we just need to remember? Absolutely not! That's how JavaScript works!
Lets take a look at a code snippet below:
const someFunction = () => { const square = (number) => number * number; return ( square(5) square(3) ) }
The following function won't work and we will get the "Uncaught SyntaxError: Unexpected identifier" error. It is just a syntactically invalid code (3) and it has nothing to do with React.
The same problem applies to the situation when we are trying to return multiple elements. JSX syntax is just syntactic sugar (4). Every JSX element will be compiled by Babel to React.createElement() call. So as you can see in the snippets below, we are ending up with te same case as in the someFunction example.
The same problem applies to the situation when we are trying to return multiple elements. JSX syntax is just syntactic sugar (4). Every JSX element will be compiled by Babel to React.createElement() call. So as you can see in the snippets below, we are ending up with te same case as in the someFunction example.
const SomeComponent = () => { return ( React.createElement(FirstElement) React.createElement(SecondElement) ) }
Sources: