Hacker News new | past | comments | ask | show | jobs | submit login
Why must JSX expressions have only ONE parent element? (dillionmegida.com)
7 points by stanulilic on April 23, 2022 | hide | past | favorite | 1 comment



There are a few things wrong, or at least only partially right, in this post.

> JSX stands for JavaScript XML

This is a decent mental model for the syntax, but I’m not sure if this has ever explicitly been the case. It’s not used in the JSX specification or on the React page dedicated to JSX. It is, oddly, used on the Wikipedia page. The specification describes it as “an XML-like syntax extension to ECMAScript without any defined semantics”.

> JSX is syntactic sugar for React.createElement

This has been a common default, although it’s increasingly common to use the new JSX transform which is syntactic sugar for `jsx`. But, as quoted from the spec, it has “no defined semantics”, and it’s often used in other ways. Sometimes as syntactic sugar for another library’s function with similar semantics (eg with Preact’s `h`/`jsx`), and even sometimes not directly analogous to a function at all (as with SolidJS/dom-expressions).

> This is why JSX expressions must have only one parent.

It’s a perfectly reasonable explanation, possibly one others will find more helpful. But it’s incomplete, and its completeness would require far less detail. The answer, again, can be found in the spec:

> JSX extends the PrimaryExpression in the ECMAScript (ECMA-262) grammar:

> Syntax

> PrimaryExpression :

> JSXElement

> JSXFragment

That’s it. JSX is an expression, which is either a JSXElement or a JSXFragment. Any two expressions in a return statement is a syntax error, e.g.

  return (
    1
    2
  );
React produces a different error, probably more helpful than the default because it guides the developer towards a solution. But this is still the answer.

Is it overly pedantic to correct this? Maybe, but I think it might be valuable for some. If nothing else, it might help folks encountering JSX used in less conventional ways.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: