Typescript: JSX Spec has been updated (Fragment syntax)

Created on 11 Oct 2017  路  8Comments  路  Source: microsoft/TypeScript

The JSX spec has been updated to support Fragments, which are a shorthand syntax for using a specific opaque class from the React package. Spec PR is at https://github.com/facebook/jsx/pull/93.

Fragments are written by completely empty tags (only whitespace is allowed between < and >), and look like <>{'child1'}{'child2'}{'child3'}</>. This is not written down in the PR's text itself as it is only an AST update, but according to https://github.com/facebook/jsx/pull/93#issuecomment-333220513 it should desugar to <React.Fragment>{'child1'}{'child2'}{'child3'}</React.Fragment>.

The intent is to make returning multiple elements from a component more ergonomic -- instead of returning an array where each child needs to be keyed, return a fragment that preserves the optional key reconciling behavior.

Committed JSTSX Suggestion

Most helpful comment

Would a --jsxFragmentFactory option be needed as well for keeping compatibility with alternative JSX libraries?

All 8 comments

Thanks for actually providing an explanation @Kovensky! I'll note that the author also elaborated here as well.

Just wanted to point out that since comments are treated as whitespace in Javascript, they're also allowed between < and >. For example, the following is valid:

< /*
 I'm a multiline comment
*/
>
</>

Sounds good. A few questions:

  • What's the emit under --jsx react ? React.createElement(React.Fragment, ...) ?
  • Under --jsx preserve, should we exactly preserve <>, or emit <React.Fragment> ?
  • Confirming that <> is not allowed to have any attributes

@RyanCavanaugh I think I can answer a few of those:

What's the emit under --jsx react ? React.createElement(React.Fragment, ...) ?

Yup.

Confirming that <> is not allowed to have any attributes

Yup.

Preserve <> would be best; but would be incompatible with tooling that has not yet been updated to support it. Emitting <React.Fragment> would be backwards-compatible but is not really preserving JSX, is it? :)

Maybe --jsx preserve-jsx1 (or just --jsx jsx1) for converting to <React.Fragment>, with --jsx preserve preserving the input as <>.

EDIT: Preserving <> is important in case the user is using JSX with another library that has its own native fragment that is not React.Fragment.

I think the EDIT above is the key point. Let's stick with <> for preserve emit.

Would a --jsxFragmentFactory option be needed as well for keeping compatibility with alternative JSX libraries?

Referencing https://github.com/facebook/jsx/pull/94 here so I don't forget about it. :)

Was this page helpful?
0 / 5 - 0 ratings