Why does JSX only allow one outer element?


#1

Question

Why does JSX only allow one outer element?

Answer

It is not just about JSX, it is a JavaScript limitation that affects JSX.
In JavaScript, a function can only return one expression by design, for example:

function textJoin(text, txt){
  return `${text} ${txt}`;
}

console.log(textJoin('this', 'is'))// returns and logs `this is`

if we were to say:

...
 return text
 return txt
...

or

  return text, txt

We will encounter that the first one will only read the first return and the second one will only return the last value (txt), yet if we get rid of the comma we will encounter an error:
SyntaxError: Unexpected token, expected ;

Since JSX is still JavaScript, its return can only handle one expression therefore to return more than one element we need to wrap it in another (an outer element), which most commonly will be a <div></div>.